org.el 956 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233
  1. ;;; org.el --- Outline-based notes management and organizer
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2015 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org-mode develops organizational tasks around NOTES files that contain
  29. ;; information about projects as plain text. Org-mode is implemented on
  30. ;; top of outline-mode, which makes it possible to keep the content of
  31. ;; large files well structured. Visibility cycling and structure editing
  32. ;; help to work with the tree. Tables are easily created with a built-in
  33. ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
  34. ;; and scheduling. It dynamically compiles entries into an agenda that
  35. ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
  36. ;; Plain text URL-like links connect to websites, emails, Usenet
  37. ;; messages, BBDB entries, and any files related to the projects. For
  38. ;; printing and sharing of notes, an Org-mode file can be exported as a
  39. ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
  40. ;; iCalendar file. It can also serve as a publishing tool for a set of
  41. ;; linked webpages.
  42. ;;
  43. ;; Installation and Activation
  44. ;; ---------------------------
  45. ;; See the corresponding sections in the manual at
  46. ;;
  47. ;; http://orgmode.org/org.html#Installation
  48. ;;
  49. ;; Documentation
  50. ;; -------------
  51. ;; The documentation of Org-mode can be found in the TeXInfo file. The
  52. ;; distribution also contains a PDF version of it. At the homepage of
  53. ;; Org-mode, you can read the same text online as HTML. There is also an
  54. ;; excellent reference card made by Philip Rooke. This card can be found
  55. ;; in the etc/ directory of Emacs 22.
  56. ;;
  57. ;; A list of recent changes can be found at
  58. ;; http://orgmode.org/Changes.html
  59. ;;
  60. ;;; Code:
  61. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  62. (defvar-local org-table-formula-constants-local nil
  63. "Local version of `org-table-formula-constants'.")
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile
  67. (require 'cl)
  68. (require 'gnus-sum))
  69. (require 'calendar)
  70. (require 'find-func)
  71. (require 'format-spec)
  72. (or (equal this-command 'eval-buffer)
  73. (condition-case nil
  74. (load (concat (file-name-directory load-file-name)
  75. "org-loaddefs.el")
  76. nil t t t)
  77. (error
  78. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  79. (sit-for 3)
  80. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  81. (sit-for 3))))
  82. (require 'org-macs)
  83. (require 'org-compat)
  84. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  85. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  86. ;;
  87. ;; In Org buffers, the value of `outline-regexp' is that of
  88. ;; `org-outline-regexp'. The only function still directly relying on
  89. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  90. ;; job when `orgstruct-mode' is active.
  91. (defvar org-outline-regexp "\\*+ "
  92. "Regexp to match Org headlines.")
  93. (defvar org-outline-regexp-bol "^\\*+ "
  94. "Regexp to match Org headlines.
  95. This is similar to `org-outline-regexp' but additionally makes
  96. sure that we are at the beginning of the line.")
  97. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  98. "Matches a headline, putting stars and text into groups.
  99. Stars are put in group 1 and the trimmed body in group 2.")
  100. ;; Emacs 22 calendar compatibility: Make sure the new variables are available
  101. (unless (boundp 'calendar-view-holidays-initially-flag)
  102. (org-defvaralias 'calendar-view-holidays-initially-flag
  103. 'view-calendar-holidays-initially))
  104. (unless (boundp 'calendar-view-diary-initially-flag)
  105. (org-defvaralias 'calendar-view-diary-initially-flag
  106. 'view-diary-entries-initially))
  107. (unless (boundp 'diary-fancy-buffer)
  108. (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
  109. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  110. (declare-function org-add-archive-files "org-archive" (files))
  111. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  112. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
  113. (declare-function org-agenda-redo "org-agenda" (&optional all))
  114. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
  115. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  116. (declare-function org-beamer-mode "ox-beamer" ())
  117. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  118. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  119. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  120. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  121. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  122. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  123. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  124. (declare-function org-clock-update-time-maybe "org-clock" ())
  125. (declare-function org-clocktable-shift "org-clock" (dir n))
  126. (declare-function org-element-at-point "org-element" ())
  127. (declare-function org-element-cache-refresh "org-element" (pos))
  128. (declare-function org-element-cache-reset "org-element" (&optional all))
  129. (declare-function org-element-contents "org-element" (element))
  130. (declare-function org-element-context "org-element" (&optional element))
  131. (declare-function org-element-copy "org-element" (datum))
  132. (declare-function org-element-interpret-data "org-element" (data &optional parent))
  133. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  134. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  135. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  136. (declare-function org-element-property "org-element" (property element))
  137. (declare-function org-element-put-property "org-element" (element property value))
  138. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  139. (declare-function org-element-type "org-element" (element))
  140. (declare-function org-element-update-syntax "org-element" ())
  141. (declare-function org-id-find-id-file "org-id" (id))
  142. (declare-function org-id-get-create "org-id" (&optional force))
  143. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  144. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  145. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  146. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  147. (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
  148. (declare-function org-table-align "org-table" ())
  149. (declare-function org-table-begin "org-table" (&optional table-type))
  150. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  151. (declare-function org-table-blank-field "org-table" ())
  152. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  153. (declare-function org-table-edit-field "org-table" (arg))
  154. (declare-function org-table-end "org-table" (&optional table-type))
  155. (declare-function org-table-end-of-field "org-table" (&optional n))
  156. (declare-function org-table-insert-row "org-table" (&optional arg))
  157. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  158. (declare-function org-table-maybe-eval-formula "org-table" ())
  159. (declare-function org-table-maybe-recalculate-line "org-table" ())
  160. (declare-function org-table-next-row "org-table" ())
  161. (declare-function org-table-paste-rectangle "org-table" ())
  162. (declare-function org-table-wrap-region "org-table" (arg))
  163. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  164. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  165. (declare-function orgtbl-mode "org-table" (&optional arg))
  166. (defsubst org-uniquify (list)
  167. "Non-destructively remove duplicate elements from LIST."
  168. (let ((res (copy-sequence list))) (delete-dups res)))
  169. (defsubst org-get-at-bol (property)
  170. "Get text property PROPERTY at the beginning of line."
  171. (get-text-property (point-at-bol) property))
  172. (defsubst org-trim (s)
  173. "Remove whitespace at the beginning and the end of string S."
  174. (replace-regexp-in-string
  175. "\\`[ \t\n\r]+" ""
  176. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  177. ;; load languages based on value of `org-babel-load-languages'
  178. (defvar org-babel-load-languages)
  179. ;;;###autoload
  180. (defun org-babel-do-load-languages (sym value)
  181. "Load the languages defined in `org-babel-load-languages'."
  182. (set-default sym value)
  183. (mapc (lambda (pair)
  184. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  185. (if active
  186. (progn
  187. (require (intern (concat "ob-" lang))))
  188. (progn
  189. (funcall 'fmakunbound
  190. (intern (concat "org-babel-execute:" lang)))
  191. (funcall 'fmakunbound
  192. (intern (concat "org-babel-expand-body:" lang)))))))
  193. org-babel-load-languages))
  194. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  195. ;;;###autoload
  196. (defun org-babel-load-file (file &optional compile)
  197. "Load Emacs Lisp source code blocks in the Org-mode FILE.
  198. This function exports the source code using `org-babel-tangle'
  199. and then loads the resulting file using `load-file'. With prefix
  200. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  201. file to byte-code before it is loaded."
  202. (interactive "fFile to load: \nP")
  203. (let* ((age (lambda (file)
  204. (float-time
  205. (time-subtract (current-time)
  206. (nth 5 (or (file-attributes (file-truename file))
  207. (file-attributes file)))))))
  208. (base-name (file-name-sans-extension file))
  209. (exported-file (concat base-name ".el")))
  210. ;; tangle if the org-mode file is newer than the elisp file
  211. (unless (and (file-exists-p exported-file)
  212. (> (funcall age file) (funcall age exported-file)))
  213. ;; Tangle-file traversal returns reversed list of tangled files
  214. ;; and we want to evaluate the first target.
  215. (setq exported-file
  216. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  217. (message "%s %s"
  218. (if compile
  219. (progn (byte-compile-file exported-file 'load)
  220. "Compiled and loaded")
  221. (progn (load-file exported-file) "Loaded"))
  222. exported-file)))
  223. (defcustom org-babel-load-languages '((emacs-lisp . t))
  224. "Languages which can be evaluated in Org-mode buffers.
  225. This list can be used to load support for any of the languages
  226. below, note that each language will depend on a different set of
  227. system executables and/or Emacs modes. When a language is
  228. \"loaded\", then code blocks in that language can be evaluated
  229. with `org-babel-execute-src-block' bound by default to C-c
  230. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  231. be set to remove code block evaluation from the C-c C-c
  232. keybinding. By default only Emacs Lisp (which has no
  233. requirements) is loaded."
  234. :group 'org-babel
  235. :set 'org-babel-do-load-languages
  236. :version "24.1"
  237. :type '(alist :tag "Babel Languages"
  238. :key-type
  239. (choice
  240. (const :tag "Awk" awk)
  241. (const :tag "C" C)
  242. (const :tag "R" R)
  243. (const :tag "Asymptote" asymptote)
  244. (const :tag "Calc" calc)
  245. (const :tag "Clojure" clojure)
  246. (const :tag "CSS" css)
  247. (const :tag "Ditaa" ditaa)
  248. (const :tag "Dot" dot)
  249. (const :tag "Emacs Lisp" emacs-lisp)
  250. (const :tag "Forth" forth)
  251. (const :tag "Fortran" fortran)
  252. (const :tag "Gnuplot" gnuplot)
  253. (const :tag "Haskell" haskell)
  254. (const :tag "IO" io)
  255. (const :tag "J" J)
  256. (const :tag "Java" java)
  257. (const :tag "Javascript" js)
  258. (const :tag "LaTeX" latex)
  259. (const :tag "Ledger" ledger)
  260. (const :tag "Lilypond" lilypond)
  261. (const :tag "Lisp" lisp)
  262. (const :tag "Makefile" makefile)
  263. (const :tag "Maxima" maxima)
  264. (const :tag "Matlab" matlab)
  265. (const :tag "Mscgen" mscgen)
  266. (const :tag "Ocaml" ocaml)
  267. (const :tag "Octave" octave)
  268. (const :tag "Org" org)
  269. (const :tag "Perl" perl)
  270. (const :tag "Pico Lisp" picolisp)
  271. (const :tag "PlantUML" plantuml)
  272. (const :tag "Python" python)
  273. (const :tag "Ruby" ruby)
  274. (const :tag "Sass" sass)
  275. (const :tag "Scala" scala)
  276. (const :tag "Scheme" scheme)
  277. (const :tag "Screen" screen)
  278. (const :tag "Shell Script" shell)
  279. (const :tag "Shen" shen)
  280. (const :tag "Sql" sql)
  281. (const :tag "Sqlite" sqlite)
  282. (const :tag "Stan" stan)
  283. (const :tag "ebnf2ps" ebnf2ps))
  284. :value-type (boolean :tag "Activate" :value t)))
  285. ;;;; Customization variables
  286. (defcustom org-clone-delete-id nil
  287. "Remove ID property of clones of a subtree.
  288. When non-nil, clones of a subtree don't inherit the ID property.
  289. Otherwise they inherit the ID property with a new unique
  290. identifier."
  291. :type 'boolean
  292. :version "24.1"
  293. :group 'org-id)
  294. ;;; Version
  295. (org-check-version)
  296. ;;;###autoload
  297. (defun org-version (&optional here full message)
  298. "Show the org-mode version.
  299. Interactively, or when MESSAGE is non-nil, show it in echo area.
  300. With prefix argument, or when HERE is non-nil, insert it at point.
  301. In non-interactive uses, a reduced version string is output unless
  302. FULL is given."
  303. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  304. (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
  305. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  306. (load-suffixes (list ".el"))
  307. (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
  308. (org-trash (or
  309. (and (fboundp 'org-release) (fboundp 'org-git-version))
  310. (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
  311. (load-suffixes save-load-suffixes)
  312. (org-version (org-release))
  313. (git-version (org-git-version))
  314. (version (format "Org-mode version %s (%s @ %s)"
  315. org-version
  316. git-version
  317. (if org-install-dir
  318. (if (string= org-dir org-install-dir)
  319. org-install-dir
  320. (concat "mixed installation! " org-install-dir " and " org-dir))
  321. "org-loaddefs.el can not be found!")))
  322. (version1 (if full version org-version)))
  323. (when here (insert version1))
  324. (when message (message "%s" version1))
  325. version1))
  326. (defconst org-version (org-version))
  327. ;;; Syntax Constants
  328. ;;;; Block
  329. (defconst org-block-regexp
  330. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  331. "Regular expression for hiding blocks.")
  332. (defconst org-dblock-start-re
  333. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  334. "Matches the start line of a dynamic block, with parameters.")
  335. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  336. "Matches the end of a dynamic block.")
  337. ;;;; Clock and Planning
  338. (defconst org-clock-string "CLOCK:"
  339. "String used as prefix for timestamps clocking work hours on an item.")
  340. (defvar org-closed-string "CLOSED:"
  341. "String used as the prefix for timestamps logging closing a TODO entry.")
  342. (defvar org-deadline-string "DEADLINE:"
  343. "String to mark deadline entries.
  344. A deadline is this string, followed by a time stamp. Should be a word,
  345. terminated by a colon. You can insert a schedule keyword and
  346. a timestamp with \\[org-deadline].")
  347. (defvar org-scheduled-string "SCHEDULED:"
  348. "String to mark scheduled TODO entries.
  349. A schedule is this string, followed by a time stamp. Should be a word,
  350. terminated by a colon. You can insert a schedule keyword and
  351. a timestamp with \\[org-schedule].")
  352. (defconst org-ds-keyword-length
  353. (+ 2
  354. (apply #'max
  355. (mapcar #'length
  356. (list org-deadline-string org-scheduled-string
  357. org-clock-string org-closed-string))))
  358. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  359. (defconst org-planning-line-re
  360. (concat "^[ \t]*"
  361. (regexp-opt
  362. (list org-closed-string org-deadline-string org-scheduled-string)
  363. t))
  364. "Matches a line with planning info.
  365. Matched keyword is in group 1.")
  366. (defconst org-clock-line-re
  367. (concat "^[ \t]*" org-clock-string)
  368. "Matches a line with clock info.")
  369. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  370. "Matches the DEADLINE keyword.")
  371. (defconst org-deadline-time-regexp
  372. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  373. "Matches the DEADLINE keyword together with a time stamp.")
  374. (defconst org-deadline-time-hour-regexp
  375. (concat "\\<" org-deadline-string
  376. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  377. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  378. (defconst org-deadline-line-regexp
  379. (concat "\\<\\(" org-deadline-string "\\).*")
  380. "Matches the DEADLINE keyword and the rest of the line.")
  381. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  382. "Matches the SCHEDULED keyword.")
  383. (defconst org-scheduled-time-regexp
  384. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  385. "Matches the SCHEDULED keyword together with a time stamp.")
  386. (defconst org-scheduled-time-hour-regexp
  387. (concat "\\<" org-scheduled-string
  388. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  389. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  390. (defconst org-closed-time-regexp
  391. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  392. "Matches the CLOSED keyword together with a time stamp.")
  393. (defconst org-keyword-time-regexp
  394. (concat "\\<"
  395. (regexp-opt
  396. (list org-scheduled-string org-deadline-string org-closed-string
  397. org-clock-string)
  398. t)
  399. " *[[<]\\([^]>]+\\)[]>]")
  400. "Matches any of the 4 keywords, together with the time stamp.")
  401. (defconst org-keyword-time-not-clock-regexp
  402. (concat
  403. "\\<"
  404. (regexp-opt
  405. (list org-scheduled-string org-deadline-string org-closed-string) t)
  406. " *[[<]\\([^]>]+\\)[]>]")
  407. "Matches any of the 3 keywords, together with the time stamp.")
  408. (defconst org-maybe-keyword-time-regexp
  409. (concat "\\(\\<"
  410. (regexp-opt
  411. (list org-scheduled-string org-deadline-string org-closed-string
  412. org-clock-string)
  413. t)
  414. "\\)?"
  415. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  416. "\\|"
  417. "<%%([^\r\n>]*>\\)")
  418. "Matches a timestamp, possibly preceded by a keyword.")
  419. (defconst org-all-time-keywords
  420. (mapcar (lambda (w) (substring w 0 -1))
  421. (list org-scheduled-string org-deadline-string
  422. org-clock-string org-closed-string))
  423. "List of time keywords.")
  424. ;;;; Drawer
  425. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  426. "Matches first or last line of a hidden block.
  427. Group 1 contains drawer's name or \"END\".")
  428. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  429. "Regular expression matching the first line of a property drawer.")
  430. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  431. "Regular expression matching the last line of a property drawer.")
  432. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  433. "Regular expression matching the first line of a clock drawer.")
  434. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  435. "Regular expression matching the last line of a clock drawer.")
  436. (defconst org-property-drawer-re
  437. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  438. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  439. "[ \t]*:END:[ \t]*$")
  440. "Matches an entire property drawer.")
  441. (defconst org-clock-drawer-re
  442. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  443. org-clock-drawer-end-re "\\)\n?")
  444. "Matches an entire clock drawer.")
  445. ;;;; Headline
  446. (defconst org-heading-keyword-regexp-format
  447. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  448. "Printf format for a regexp matching a headline with some keyword.
  449. This regexp will match the headline of any node which has the
  450. exact keyword that is put into the format. The keyword isn't in
  451. any group by default, but the stars and the body are.")
  452. (defconst org-heading-keyword-maybe-regexp-format
  453. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  454. "Printf format for a regexp matching a headline, possibly with some keyword.
  455. This regexp can match any headline with the specified keyword, or
  456. without a keyword. The keyword isn't in any group by default,
  457. but the stars and the body are.")
  458. (defconst org-archive-tag "ARCHIVE"
  459. "The tag that marks a subtree as archived.
  460. An archived subtree does not open during visibility cycling, and does
  461. not contribute to the agenda listings.")
  462. (defconst org-comment-string "COMMENT"
  463. "Entries starting with this keyword will never be exported.
  464. An entry can be toggled between COMMENT and normal with
  465. \\[org-toggle-comment].")
  466. ;;;; LaTeX Environments and Fragments
  467. (defconst org-latex-regexps
  468. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  469. ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
  470. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  471. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  472. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  473. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  474. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  475. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  476. "Regular expressions for matching embedded LaTeX.")
  477. ;;;; Node Property
  478. (defconst org-effort-property "Effort"
  479. "The property that is being used to keep track of effort estimates.
  480. Effort estimates given in this property need to have the format H:MM.")
  481. ;;;; Table
  482. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  483. "Detect an org-type or table-type table.")
  484. (defconst org-table-line-regexp "^[ \t]*|"
  485. "Detect an org-type table line.")
  486. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  487. "Detect an org-type table line.")
  488. (defconst org-table-hline-regexp "^[ \t]*|-"
  489. "Detect an org-type table hline.")
  490. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  491. "Detect a table-type table hline.")
  492. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  493. "Detect the first line outside a table when searching from within it.
  494. This works for both table types.")
  495. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  496. "Detect a #+TBLFM line.")
  497. ;;;; Timestamp
  498. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  499. "Regular expression for fast time stamp matching.")
  500. (defconst org-ts-regexp-inactive
  501. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  502. "Regular expression for fast inactive time stamp matching.")
  503. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  504. "Regular expression for fast time stamp matching.")
  505. (defconst org-ts-regexp0
  506. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  507. "Regular expression matching time strings for analysis.
  508. This one does not require the space after the date, so it can be used
  509. on a string that terminates immediately after the date.")
  510. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  511. "Regular expression matching time strings for analysis.")
  512. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  513. "Regular expression matching time stamps, with groups.")
  514. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  515. "Regular expression matching time stamps (also [..]), with groups.")
  516. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  517. "Regular expression matching a time stamp range.")
  518. (defconst org-tr-regexp-both
  519. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  520. "Regular expression matching a time stamp range.")
  521. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  522. org-ts-regexp "\\)?")
  523. "Regular expression matching a time stamp or time stamp range.")
  524. (defconst org-tsr-regexp-both
  525. (concat org-ts-regexp-both "\\(--?-?"
  526. org-ts-regexp-both "\\)?")
  527. "Regular expression matching a time stamp or time stamp range.
  528. The time stamps may be either active or inactive.")
  529. (defconst org-repeat-re
  530. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  531. "Regular expression for specifying repeated events.
  532. After a match, group 1 contains the repeat expression.")
  533. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  534. "Formats for `format-time-string' which are used for time stamps.")
  535. ;;; The custom variables
  536. (defgroup org nil
  537. "Outline-based notes management and organizer."
  538. :tag "Org"
  539. :group 'outlines
  540. :group 'calendar)
  541. (defcustom org-mode-hook nil
  542. "Mode hook for Org-mode, run after the mode was turned on."
  543. :group 'org
  544. :type 'hook)
  545. (defcustom org-load-hook nil
  546. "Hook that is run after org.el has been loaded."
  547. :group 'org
  548. :type 'hook)
  549. (defcustom org-log-buffer-setup-hook nil
  550. "Hook that is run after an Org log buffer is created."
  551. :group 'org
  552. :version "24.1"
  553. :type 'hook)
  554. (defvar org-modules) ; defined below
  555. (defvar org-modules-loaded nil
  556. "Have the modules been loaded already?")
  557. (defun org-load-modules-maybe (&optional force)
  558. "Load all extensions listed in `org-modules'."
  559. (when (or force (not org-modules-loaded))
  560. (mapc (lambda (ext)
  561. (condition-case nil (require ext)
  562. (error (message "Problems while trying to load feature `%s'" ext))))
  563. org-modules)
  564. (setq org-modules-loaded t)))
  565. (defun org-set-modules (var value)
  566. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  567. (set var value)
  568. (when (featurep 'org)
  569. (org-load-modules-maybe 'force)
  570. (org-element-cache-reset 'all)))
  571. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  572. "Modules that should always be loaded together with org.el.
  573. If a description starts with <C>, the file is not part of Emacs
  574. and loading it will require that you have downloaded and properly
  575. installed the Org mode distribution.
  576. You can also use this system to load external packages (i.e. neither Org
  577. core modules, nor modules from the CONTRIB directory). Just add symbols
  578. to the end of the list. If the package is called org-xyz.el, then you need
  579. to add the symbol `xyz', and the package must have a call to:
  580. (provide \\='org-xyz)
  581. For export specific modules, see also `org-export-backends'."
  582. :group 'org
  583. :set 'org-set-modules
  584. :version "24.4"
  585. :package-version '(Org . "8.0")
  586. :type
  587. '(set :greedy t
  588. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  589. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  590. (const :tag " crypt: Encryption of subtrees" org-crypt)
  591. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  592. (const :tag " docview: Links to doc-view buffers" org-docview)
  593. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  594. (const :tag " habit: Track your consistency with habits" org-habit)
  595. (const :tag " id: Global IDs for identifying entries" org-id)
  596. (const :tag " info: Links to Info nodes" org-info)
  597. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  598. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  599. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  600. (const :tag " mouse: Additional mouse support" org-mouse)
  601. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  602. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  603. (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
  604. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  605. (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
  606. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  607. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  608. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  609. (const :tag "C collector: Collect properties into tables" org-collector)
  610. (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  611. (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
  612. (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
  613. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  614. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  615. (const :tag "C eval: Include command output as text" org-eval)
  616. (const :tag "C eww: Store link to url of eww" org-eww)
  617. (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
  618. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  619. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  620. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  621. (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
  622. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  623. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  624. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  625. (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
  626. (const :tag "C man: Support for links to manpages in Org-mode" org-man)
  627. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  628. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  629. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  630. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  631. (const :tag "C registry: A registry for Org-mode links" org-registry)
  632. (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
  633. (const :tag "C secretary: Team management with org-mode" org-secretary)
  634. (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
  635. (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
  636. (const :tag "C track: Keep up with Org-mode development" org-track)
  637. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  638. (const :tag "C vm: Links to VM folders/messages" org-vm)
  639. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  640. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  641. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  642. (defvar org-export-registered-backends) ; From ox.el.
  643. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  644. (declare-function org-export-backend-name "ox" (backend))
  645. (defcustom org-export-backends '(ascii html icalendar latex)
  646. "List of export back-ends that should be always available.
  647. If a description starts with <C>, the file is not part of Emacs
  648. and loading it will require that you have downloaded and properly
  649. installed the Org mode distribution.
  650. Unlike to `org-modules', libraries in this list will not be
  651. loaded along with Org, but only once the export framework is
  652. needed.
  653. This variable needs to be set before org.el is loaded. If you
  654. need to make a change while Emacs is running, use the customize
  655. interface or run the following code, where VAL stands for the new
  656. value of the variable, after updating it:
  657. (progn
  658. (setq org-export-registered-backends
  659. (cl-remove-if-not
  660. (lambda (backend)
  661. (let ((name (org-export-backend-name backend)))
  662. (or (memq name val)
  663. (catch \\='parentp
  664. (dolist (b val)
  665. (and (org-export-derived-backend-p b name)
  666. (throw \\='parentp t)))))))
  667. org-export-registered-backends))
  668. (let ((new-list (mapcar #\\='org-export-backend-name
  669. org-export-registered-backends)))
  670. (dolist (backend val)
  671. (cond
  672. ((not (load (format \"ox-%s\" backend) t t))
  673. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  674. backend))
  675. ((not (memq backend new-list)) (push backend new-list))))
  676. (set-default \\='org-export-backends new-list)))
  677. Adding a back-end to this list will also pull the back-end it
  678. depends on, if any."
  679. :group 'org
  680. :group 'org-export
  681. :version "24.4"
  682. :package-version '(Org . "8.0")
  683. :initialize 'custom-initialize-set
  684. :set (lambda (var val)
  685. (if (not (featurep 'ox)) (set-default var val)
  686. ;; Any back-end not required anymore (not present in VAL and not
  687. ;; a parent of any back-end in the new value) is removed from the
  688. ;; list of registered back-ends.
  689. (setq org-export-registered-backends
  690. (cl-remove-if-not
  691. (lambda (backend)
  692. (let ((name (org-export-backend-name backend)))
  693. (or (memq name val)
  694. (catch 'parentp
  695. (dolist (b val)
  696. (and (org-export-derived-backend-p b name)
  697. (throw 'parentp t)))))))
  698. org-export-registered-backends))
  699. ;; Now build NEW-LIST of both new back-ends and required
  700. ;; parents.
  701. (let ((new-list (mapcar #'org-export-backend-name
  702. org-export-registered-backends)))
  703. (dolist (backend val)
  704. (cond
  705. ((not (load (format "ox-%s" backend) t t))
  706. (message "Problems while trying to load export back-end `%s'"
  707. backend))
  708. ((not (memq backend new-list)) (push backend new-list))))
  709. ;; Set VAR to that list with fixed dependencies.
  710. (set-default var new-list))))
  711. :type '(set :greedy t
  712. (const :tag " ascii Export buffer to ASCII format" ascii)
  713. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  714. (const :tag " html Export buffer to HTML format" html)
  715. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  716. (const :tag " latex Export buffer to LaTeX format" latex)
  717. (const :tag " man Export buffer to MAN format" man)
  718. (const :tag " md Export buffer to Markdown format" md)
  719. (const :tag " odt Export buffer to ODT format" odt)
  720. (const :tag " org Export buffer to Org format" org)
  721. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  722. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  723. (const :tag "C deck Export buffer to deck.js presentations" deck)
  724. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  725. (const :tag "C groff Export buffer to Groff format" groff)
  726. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  727. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  728. (const :tag "C s5 Export buffer to s5 presentations" s5)
  729. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  730. (eval-after-load 'ox
  731. '(mapc
  732. (lambda (backend)
  733. (condition-case nil (require (intern (format "ox-%s" backend)))
  734. (error (message "Problems while trying to load export back-end `%s'"
  735. backend))))
  736. org-export-backends))
  737. (defcustom org-support-shift-select nil
  738. "Non-nil means make shift-cursor commands select text when possible.
  739. \\<org-mode-map>\
  740. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  741. start selecting a region, or enlarge regions started in this way.
  742. In Org-mode, in special contexts, these same keys are used for
  743. other purposes, important enough to compete with shift selection.
  744. Org tries to balance these needs by supporting `shift-select-mode'
  745. outside these special contexts, under control of this variable.
  746. The default of this variable is nil, to avoid confusing behavior. Shifted
  747. cursor keys will then execute Org commands in the following contexts:
  748. - on a headline, changing TODO state (left/right) and priority (up/down)
  749. - on a time stamp, changing the time
  750. - in a plain list item, changing the bullet type
  751. - in a property definition line, switching between allowed values
  752. - in the BEGIN line of a clock table (changing the time block).
  753. Outside these contexts, the commands will throw an error.
  754. When this variable is t and the cursor is not in a special
  755. context, Org-mode will support shift-selection for making and
  756. enlarging regions. To make this more effective, the bullet
  757. cycling will no longer happen anywhere in an item line, but only
  758. if the cursor is exactly on the bullet.
  759. If you set this variable to the symbol `always', then the keys
  760. will not be special in headlines, property lines, and item lines,
  761. to make shift selection work there as well. If this is what you
  762. want, you can use the following alternative commands:
  763. `\\[org-todo]' and `\\[org-priority]' \
  764. to change TODO state and priority,
  765. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  766. can be used to switch TODO sets,
  767. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  768. and properties can be edited by hand or in column view.
  769. However, when the cursor is on a timestamp, shift-cursor commands
  770. will still edit the time stamp - this is just too good to give up.
  771. XEmacs user should have this variable set to nil, because
  772. `shift-select-mode' is in Emacs 23 or later only."
  773. :group 'org
  774. :type '(choice
  775. (const :tag "Never" nil)
  776. (const :tag "When outside special context" t)
  777. (const :tag "Everywhere except timestamps" always)))
  778. (defcustom org-loop-over-headlines-in-active-region nil
  779. "Shall some commands act upon headlines in the active region?
  780. When set to t, some commands will be performed in all headlines
  781. within the active region.
  782. When set to `start-level', some commands will be performed in all
  783. headlines within the active region, provided that these headlines
  784. are of the same level than the first one.
  785. When set to a string, those commands will be performed on the
  786. matching headlines within the active region. Such string must be
  787. a tags/property/todo match as it is used in the agenda tags view.
  788. The list of commands is: `org-schedule', `org-deadline',
  789. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  790. `org-archive-to-archive-sibling'. The archiving commands skip
  791. already archived entries."
  792. :type '(choice (const :tag "Don't loop" nil)
  793. (const :tag "All headlines in active region" t)
  794. (const :tag "In active region, headlines at the same level than the first one" start-level)
  795. (string :tag "Tags/Property/Todo matcher"))
  796. :version "24.1"
  797. :group 'org-todo
  798. :group 'org-archive)
  799. (defgroup org-startup nil
  800. "Options concerning startup of Org-mode."
  801. :tag "Org Startup"
  802. :group 'org)
  803. (defcustom org-startup-folded t
  804. "Non-nil means entering Org-mode will switch to OVERVIEW.
  805. This can also be configured on a per-file basis by adding one of
  806. the following lines anywhere in the buffer:
  807. #+STARTUP: fold (or `overview', this is equivalent)
  808. #+STARTUP: nofold (or `showall', this is equivalent)
  809. #+STARTUP: content
  810. #+STARTUP: showeverything
  811. By default, this option is ignored when Org opens agenda files
  812. for the first time. If you want the agenda to honor the startup
  813. option, set `org-agenda-inhibit-startup' to nil."
  814. :group 'org-startup
  815. :type '(choice
  816. (const :tag "nofold: show all" nil)
  817. (const :tag "fold: overview" t)
  818. (const :tag "content: all headlines" content)
  819. (const :tag "show everything, even drawers" showeverything)))
  820. (defcustom org-startup-truncated t
  821. "Non-nil means entering Org-mode will set `truncate-lines'.
  822. This is useful since some lines containing links can be very long and
  823. uninteresting. Also tables look terrible when wrapped."
  824. :group 'org-startup
  825. :type 'boolean)
  826. (defcustom org-startup-indented nil
  827. "Non-nil means turn on `org-indent-mode' on startup.
  828. This can also be configured on a per-file basis by adding one of
  829. the following lines anywhere in the buffer:
  830. #+STARTUP: indent
  831. #+STARTUP: noindent"
  832. :group 'org-structure
  833. :type '(choice
  834. (const :tag "Not" nil)
  835. (const :tag "Globally (slow on startup in large files)" t)))
  836. (defcustom org-use-sub-superscripts t
  837. "Non-nil means interpret \"_\" and \"^\" for display.
  838. If you want to control how Org exports those characters, see
  839. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  840. used to be an alias for `org-export-with-sub-superscripts' in
  841. Org <8.0, it is not anymore.
  842. When this option is turned on, you can use TeX-like syntax for
  843. sub- and superscripts within the buffer. Several characters after
  844. \"_\" or \"^\" will be considered as a single item - so grouping
  845. with {} is normally not needed. For example, the following things
  846. will be parsed as single sub- or superscripts:
  847. 10^24 or 10^tau several digits will be considered 1 item.
  848. 10^-12 or 10^-tau a leading sign with digits or a word
  849. x^2-y^3 will be read as x^2 - y^3, because items are
  850. terminated by almost any nonword/nondigit char.
  851. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  852. Still, ambiguity is possible. So when in doubt, use {} to enclose
  853. the sub/superscript. If you set this variable to the symbol `{}',
  854. the braces are *required* in order to trigger interpretations as
  855. sub/superscript. This can be helpful in documents that need \"_\"
  856. frequently in plain text."
  857. :group 'org-startup
  858. :version "24.4"
  859. :package-version '(Org . "8.0")
  860. :type '(choice
  861. (const :tag "Always interpret" t)
  862. (const :tag "Only with braces" {})
  863. (const :tag "Never interpret" nil)))
  864. (defcustom org-startup-with-beamer-mode nil
  865. "Non-nil means turn on `org-beamer-mode' on startup.
  866. This can also be configured on a per-file basis by adding one of
  867. the following lines anywhere in the buffer:
  868. #+STARTUP: beamer"
  869. :group 'org-startup
  870. :version "24.1"
  871. :type 'boolean)
  872. (defcustom org-startup-align-all-tables nil
  873. "Non-nil means align all tables when visiting a file.
  874. This is useful when the column width in tables is forced with <N> cookies
  875. in table fields. Such tables will look correct only after the first re-align.
  876. This can also be configured on a per-file basis by adding one of
  877. the following lines anywhere in the buffer:
  878. #+STARTUP: align
  879. #+STARTUP: noalign"
  880. :group 'org-startup
  881. :type 'boolean)
  882. (defcustom org-startup-with-inline-images nil
  883. "Non-nil means show inline images when loading a new Org file.
  884. This can also be configured on a per-file basis by adding one of
  885. the following lines anywhere in the buffer:
  886. #+STARTUP: inlineimages
  887. #+STARTUP: noinlineimages"
  888. :group 'org-startup
  889. :version "24.1"
  890. :type 'boolean)
  891. (defcustom org-startup-with-latex-preview nil
  892. "Non-nil means preview LaTeX fragments when loading a new Org file.
  893. This can also be configured on a per-file basis by adding one of
  894. the following lines anywhere in the buffer:
  895. #+STARTUP: latexpreview
  896. #+STARTUP: nolatexpreview"
  897. :group 'org-startup
  898. :version "24.4"
  899. :package-version '(Org . "8.0")
  900. :type 'boolean)
  901. (defcustom org-insert-mode-line-in-empty-file nil
  902. "Non-nil means insert the first line setting Org-mode in empty files.
  903. When the function `org-mode' is called interactively in an empty file, this
  904. normally means that the file name does not automatically trigger Org-mode.
  905. To ensure that the file will always be in Org-mode in the future, a
  906. line enforcing Org-mode will be inserted into the buffer, if this option
  907. has been set."
  908. :group 'org-startup
  909. :type 'boolean)
  910. (defcustom org-replace-disputed-keys nil
  911. "Non-nil means use alternative key bindings for some keys.
  912. Org-mode uses S-<cursor> keys for changing timestamps and priorities.
  913. These keys are also used by other packages like shift-selection-mode'
  914. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  915. If you want to use Org-mode together with one of these other modes,
  916. or more generally if you would like to move some Org-mode commands to
  917. other keys, set this variable and configure the keys with the variable
  918. `org-disputed-keys'.
  919. This option is only relevant at load-time of Org-mode, and must be set
  920. *before* org.el is loaded. Changing it requires a restart of Emacs to
  921. become effective."
  922. :group 'org-startup
  923. :type 'boolean)
  924. (defcustom org-use-extra-keys nil
  925. "Non-nil means use extra key sequence definitions for certain commands.
  926. This happens automatically if you run XEmacs or if `window-system'
  927. is nil. This variable lets you do the same manually. You must
  928. set it before loading org.
  929. Example: on Carbon Emacs 22 running graphically, with an external
  930. keyboard on a Powerbook, the default way of setting M-left might
  931. not work for either Alt or ESC. Setting this variable will make
  932. it work for ESC."
  933. :group 'org-startup
  934. :type 'boolean)
  935. (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  936. (defcustom org-disputed-keys
  937. '(([(shift up)] . [(meta p)])
  938. ([(shift down)] . [(meta n)])
  939. ([(shift left)] . [(meta -)])
  940. ([(shift right)] . [(meta +)])
  941. ([(control shift right)] . [(meta shift +)])
  942. ([(control shift left)] . [(meta shift -)]))
  943. "Keys for which Org-mode and other modes compete.
  944. This is an alist, cars are the default keys, second element specifies
  945. the alternative to use when `org-replace-disputed-keys' is t.
  946. Keys can be specified in any syntax supported by `define-key'.
  947. The value of this option takes effect only at Org-mode's startup,
  948. therefore you'll have to restart Emacs to apply it after changing."
  949. :group 'org-startup
  950. :type 'alist)
  951. (defun org-key (key)
  952. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  953. Or return the original if not disputed.
  954. Also apply the translations defined in `org-xemacs-key-equivalents'."
  955. (when org-replace-disputed-keys
  956. (let* ((nkey (key-description key))
  957. (x (org-find-if (lambda (x)
  958. (equal (key-description (car x)) nkey))
  959. org-disputed-keys)))
  960. (setq key (if x (cdr x) key))))
  961. (when (featurep 'xemacs)
  962. (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
  963. key)
  964. (defun org-find-if (predicate seq)
  965. (catch 'exit
  966. (while seq
  967. (if (funcall predicate (car seq))
  968. (throw 'exit (car seq))
  969. (pop seq)))))
  970. (defun org-defkey (keymap key def)
  971. "Define a key, possibly translated, as returned by `org-key'."
  972. (define-key keymap (org-key key) def))
  973. (defcustom org-ellipsis nil
  974. "The ellipsis to use in the Org-mode outline.
  975. When nil, just use the standard three dots.
  976. When a string, use that string instead.
  977. When a face, use the standard 3 dots, but with the specified face.
  978. The change affects only Org-mode (which will then use its own display table).
  979. Changing this requires executing \\[org-mode] in a buffer to become
  980. effective."
  981. :group 'org-startup
  982. :type '(choice (const :tag "Default" nil)
  983. (face :tag "Face" :value org-warning)
  984. (string :tag "String" :value "...#")))
  985. (defvar org-display-table nil
  986. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  987. (defgroup org-keywords nil
  988. "Keywords in Org-mode."
  989. :tag "Org Keywords"
  990. :group 'org)
  991. (defcustom org-closed-keep-when-no-todo nil
  992. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  993. :group 'org-todo
  994. :group 'org-keywords
  995. :version "24.4"
  996. :package-version '(Org . "8.0")
  997. :type 'boolean)
  998. (defgroup org-structure nil
  999. "Options concerning the general structure of Org-mode files."
  1000. :tag "Org Structure"
  1001. :group 'org)
  1002. (defgroup org-reveal-location nil
  1003. "Options about how to make context of a location visible."
  1004. :tag "Org Reveal Location"
  1005. :group 'org-structure)
  1006. (defcustom org-show-context-detail '((isearch . lineage)
  1007. (bookmark-jump . lineage)
  1008. (default . ancestors))
  1009. "Alist between context and visibility span when revealing a location.
  1010. \\<org-mode-map>Some actions may move point into invisible
  1011. locations. As a consequence, Org always expose a neighborhood
  1012. around point. How much is shown depends on the initial action,
  1013. or context. Valid contexts are
  1014. agenda when exposing an entry from the agenda
  1015. org-goto when using the command `org-goto' (\\[org-goto])
  1016. occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
  1017. tags-tree when constructing a sparse tree based on tags matches
  1018. link-search when exposing search matches associated with a link
  1019. mark-goto when exposing the jump goal of a mark
  1020. bookmark-jump when exposing a bookmark location
  1021. isearch when exiting from an incremental search
  1022. default default for all contexts not set explicitly
  1023. Allowed visibility spans are
  1024. minimal show current headline; if point is not on headline,
  1025. also show entry
  1026. local show current headline, entry and next headline
  1027. ancestors show current headline and its direct ancestors; if
  1028. point is not on headline, also show entry
  1029. lineage show current headline, its direct ancestors and all
  1030. their children; if point is not on headline, also show
  1031. entry and first child
  1032. tree show current headline, its direct ancestors and all
  1033. their children; if point is not on headline, also show
  1034. entry and all children
  1035. canonical show current headline, its direct ancestors along with
  1036. their entries and children; if point is not located on
  1037. the headline, also show current entry and all children
  1038. As special cases, a nil or t value means show all contexts in
  1039. `minimal' or `canonical' view, respectively.
  1040. Some views can make displayed information very compact, but also
  1041. make it harder to edit the location of the match. In such
  1042. a case, use the command `org-reveal' (\\[org-reveal]) to show
  1043. more context."
  1044. :group 'org-reveal-location
  1045. :version "25.1"
  1046. :package-version '(Org . "8.3")
  1047. :type '(choice
  1048. (const :tag "Canonical" t)
  1049. (const :tag "Minimal" nil)
  1050. (repeat :greedy t :tag "Individual contexts"
  1051. (cons
  1052. (choice :tag "Context"
  1053. (const agenda)
  1054. (const org-goto)
  1055. (const occur-tree)
  1056. (const tags-tree)
  1057. (const link-search)
  1058. (const mark-goto)
  1059. (const bookmark-jump)
  1060. (const isearch)
  1061. (const default))
  1062. (choice :tag "Detail level"
  1063. (const minimal)
  1064. (const local)
  1065. (const ancestors)
  1066. (const lineage)
  1067. (const tree)
  1068. (const canonical))))))
  1069. (defcustom org-indirect-buffer-display 'other-window
  1070. "How should indirect tree buffers be displayed?
  1071. This applies to indirect buffers created with the commands
  1072. \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
  1073. Valid values are:
  1074. current-window Display in the current window
  1075. other-window Just display in another window.
  1076. dedicated-frame Create one new frame, and re-use it each time.
  1077. new-frame Make a new frame each time. Note that in this case
  1078. previously-made indirect buffers are kept, and you need to
  1079. kill these buffers yourself."
  1080. :group 'org-structure
  1081. :group 'org-agenda-windows
  1082. :type '(choice
  1083. (const :tag "In current window" current-window)
  1084. (const :tag "In current frame, other window" other-window)
  1085. (const :tag "Each time a new frame" new-frame)
  1086. (const :tag "One dedicated frame" dedicated-frame)))
  1087. (defcustom org-use-speed-commands nil
  1088. "Non-nil means activate single letter commands at beginning of a headline.
  1089. This may also be a function to test for appropriate locations where speed
  1090. commands should be active.
  1091. For example, to activate speed commands when the point is on any
  1092. star at the beginning of the headline, you can do this:
  1093. (setq org-use-speed-commands
  1094. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1095. :group 'org-structure
  1096. :type '(choice
  1097. (const :tag "Never" nil)
  1098. (const :tag "At beginning of headline stars" t)
  1099. (function)))
  1100. (defcustom org-speed-commands-user nil
  1101. "Alist of additional speed commands.
  1102. This list will be checked before `org-speed-commands-default'
  1103. when the variable `org-use-speed-commands' is non-nil
  1104. and when the cursor is at the beginning of a headline.
  1105. The car if each entry is a string with a single letter, which must
  1106. be assigned to `self-insert-command' in the global map.
  1107. The cdr is either a command to be called interactively, a function
  1108. to be called, or a form to be evaluated.
  1109. An entry that is just a list with a single string will be interpreted
  1110. as a descriptive headline that will be added when listing the speed
  1111. commands in the Help buffer using the `?' speed command."
  1112. :group 'org-structure
  1113. :type '(repeat :value ("k" . ignore)
  1114. (choice :value ("k" . ignore)
  1115. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1116. (cons :tag "Letter and Command"
  1117. (string :tag "Command letter")
  1118. (choice
  1119. (function)
  1120. (sexp))))))
  1121. (defcustom org-bookmark-names-plist
  1122. '(:last-capture "org-capture-last-stored"
  1123. :last-refile "org-refile-last-stored"
  1124. :last-capture-marker "org-capture-last-stored-marker")
  1125. "Names for bookmarks automatically set by some Org commands.
  1126. This can provide strings as names for a number of bookmarks Org sets
  1127. automatically. The following keys are currently implemented:
  1128. :last-capture
  1129. :last-capture-marker
  1130. :last-refile
  1131. When a key does not show up in the property list, the corresponding bookmark
  1132. is not set."
  1133. :group 'org-structure
  1134. :type 'plist)
  1135. (defgroup org-cycle nil
  1136. "Options concerning visibility cycling in Org-mode."
  1137. :tag "Org Cycle"
  1138. :group 'org-structure)
  1139. (defcustom org-cycle-skip-children-state-if-no-children t
  1140. "Non-nil means skip CHILDREN state in entries that don't have any."
  1141. :group 'org-cycle
  1142. :type 'boolean)
  1143. (defcustom org-cycle-max-level nil
  1144. "Maximum level which should still be subject to visibility cycling.
  1145. Levels higher than this will, for cycling, be treated as text, not a headline.
  1146. When `org-odd-levels-only' is set, a value of N in this variable actually
  1147. means 2N-1 stars as the limiting headline.
  1148. When nil, cycle all levels.
  1149. Note that the limiting level of cycling is also influenced by
  1150. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1151. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1152. than its value."
  1153. :group 'org-cycle
  1154. :type '(choice
  1155. (const :tag "No limit" nil)
  1156. (integer :tag "Maximum level")))
  1157. (defcustom org-hide-block-startup nil
  1158. "Non-nil means entering Org-mode will fold all blocks.
  1159. This can also be set in on a per-file basis with
  1160. #+STARTUP: hideblocks
  1161. #+STARTUP: showblocks"
  1162. :group 'org-startup
  1163. :group 'org-cycle
  1164. :type 'boolean)
  1165. (defcustom org-cycle-global-at-bob nil
  1166. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1167. This makes it possible to do global cycling without having to use S-TAB or
  1168. \\[universal-argument] TAB. For this special case to work, the first line
  1169. of the buffer must not be a headline -- it may be empty or some other text.
  1170. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1171. sure the cursor stays at the beginning of the buffer. When this option is
  1172. nil, don't do anything special at the beginning of the buffer."
  1173. :group 'org-cycle
  1174. :type 'boolean)
  1175. (defcustom org-cycle-level-after-item/entry-creation t
  1176. "Non-nil means cycle entry level or item indentation in new empty entries.
  1177. When the cursor is at the end of an empty headline, i.e., with only stars
  1178. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1179. and then all possible ancestor states, before returning to the original state.
  1180. This makes data entry extremely fast: M-RET to create a new headline,
  1181. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1182. When the cursor is at the end of an empty plain list item, one TAB will
  1183. make it a subitem, two or more tabs will back up to make this an item
  1184. higher up in the item hierarchy."
  1185. :group 'org-cycle
  1186. :type 'boolean)
  1187. (defcustom org-cycle-emulate-tab t
  1188. "Where should `org-cycle' emulate TAB.
  1189. nil Never
  1190. white Only in completely white lines
  1191. whitestart Only at the beginning of lines, before the first non-white char
  1192. t Everywhere except in headlines
  1193. exc-hl-bol Everywhere except at the start of a headline
  1194. If TAB is used in a place where it does not emulate TAB, the current subtree
  1195. visibility is cycled."
  1196. :group 'org-cycle
  1197. :type '(choice (const :tag "Never" nil)
  1198. (const :tag "Only in completely white lines" white)
  1199. (const :tag "Before first char in a line" whitestart)
  1200. (const :tag "Everywhere except in headlines" t)
  1201. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1202. (defcustom org-cycle-separator-lines 2
  1203. "Number of empty lines needed to keep an empty line between collapsed trees.
  1204. If you leave an empty line between the end of a subtree and the following
  1205. headline, this empty line is hidden when the subtree is folded.
  1206. Org-mode will leave (exactly) one empty line visible if the number of
  1207. empty lines is equal or larger to the number given in this variable.
  1208. So the default 2 means at least 2 empty lines after the end of a subtree
  1209. are needed to produce free space between a collapsed subtree and the
  1210. following headline.
  1211. If the number is negative, and the number of empty lines is at least -N,
  1212. all empty lines are shown.
  1213. Special case: when 0, never leave empty lines in collapsed view."
  1214. :group 'org-cycle
  1215. :type 'integer)
  1216. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1217. (defcustom org-pre-cycle-hook nil
  1218. "Hook that is run before visibility cycling is happening.
  1219. The function(s) in this hook must accept a single argument which indicates
  1220. the new state that will be set right after running this hook. The
  1221. argument is a symbol. Before a global state change, it can have the values
  1222. `overview', `content', or `all'. Before a local state change, it can have
  1223. the values `folded', `children', or `subtree'."
  1224. :group 'org-cycle
  1225. :type 'hook)
  1226. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1227. org-cycle-hide-drawers
  1228. org-cycle-show-empty-lines
  1229. org-optimize-window-after-visibility-change)
  1230. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1231. The function(s) in this hook must accept a single argument which indicates
  1232. the new state that was set by the most recent `org-cycle' command. The
  1233. argument is a symbol. After a global state change, it can have the values
  1234. `overview', `contents', or `all'. After a local state change, it can have
  1235. the values `folded', `children', or `subtree'."
  1236. :group 'org-cycle
  1237. :type 'hook
  1238. :version "25.1"
  1239. :package-version '(Org . "8.3"))
  1240. (defgroup org-edit-structure nil
  1241. "Options concerning structure editing in Org-mode."
  1242. :tag "Org Edit Structure"
  1243. :group 'org-structure)
  1244. (defcustom org-odd-levels-only nil
  1245. "Non-nil means skip even levels and only use odd levels for the outline.
  1246. This has the effect that two stars are being added/taken away in
  1247. promotion/demotion commands. It also influences how levels are
  1248. handled by the exporters.
  1249. Changing it requires restart of `font-lock-mode' to become effective
  1250. for fontification also in regions already fontified.
  1251. You may also set this on a per-file basis by adding one of the following
  1252. lines to the buffer:
  1253. #+STARTUP: odd
  1254. #+STARTUP: oddeven"
  1255. :group 'org-edit-structure
  1256. :group 'org-appearance
  1257. :type 'boolean)
  1258. (defcustom org-adapt-indentation t
  1259. "Non-nil means adapt indentation to outline node level.
  1260. When this variable is set, Org assumes that you write outlines by
  1261. indenting text in each node to align with the headline (after the
  1262. stars). The following issues are influenced by this variable:
  1263. - The indentation is increased by one space in a demotion
  1264. command, and decreased by one in a promotion command. However,
  1265. in the latter case, if shifting some line in the entry body
  1266. would alter document structure (e.g., insert a new headline),
  1267. indentation is not changed at all.
  1268. - Property drawers and planning information is inserted indented
  1269. when this variable is set. When nil, they will not be indented.
  1270. - TAB indents a line relative to current level. The lines below
  1271. a headline will be indented when this variable is set.
  1272. Note that this is all about true indentation, by adding and
  1273. removing space characters. See also `org-indent.el' which does
  1274. level-dependent indentation in a virtual way, i.e. at display
  1275. time in Emacs."
  1276. :group 'org-edit-structure
  1277. :type 'boolean)
  1278. (defcustom org-special-ctrl-a/e nil
  1279. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1280. When t, `C-a' will bring back the cursor to the beginning of the
  1281. headline text, i.e. after the stars and after a possible TODO
  1282. keyword. In an item, this will be the position after bullet and
  1283. check-box, if any. When the cursor is already at that position,
  1284. another `C-a' will bring it to the beginning of the line.
  1285. `C-e' will jump to the end of the headline, ignoring the presence
  1286. of tags in the headline. A second `C-e' will then jump to the
  1287. true end of the line, after any tags. This also means that, when
  1288. this variable is non-nil, `C-e' also will never jump beyond the
  1289. end of the heading of a folded section, i.e. not after the
  1290. ellipses.
  1291. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1292. normally, going to the true line boundary first. Only a directly
  1293. following, identical keypress will bring the cursor to the
  1294. special positions.
  1295. This may also be a cons cell where the behavior for `C-a' and
  1296. `C-e' is set separately."
  1297. :group 'org-edit-structure
  1298. :type '(choice
  1299. (const :tag "off" nil)
  1300. (const :tag "on: after stars/bullet and before tags first" t)
  1301. (const :tag "reversed: true line boundary first" reversed)
  1302. (cons :tag "Set C-a and C-e separately"
  1303. (choice :tag "Special C-a"
  1304. (const :tag "off" nil)
  1305. (const :tag "on: after stars/bullet first" t)
  1306. (const :tag "reversed: before stars/bullet first" reversed))
  1307. (choice :tag "Special C-e"
  1308. (const :tag "off" nil)
  1309. (const :tag "on: before tags first" t)
  1310. (const :tag "reversed: after tags first" reversed)))))
  1311. (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1312. (defcustom org-special-ctrl-k nil
  1313. "Non-nil means `C-k' will behave specially in headlines.
  1314. When nil, `C-k' will call the default `kill-line' command.
  1315. When t, the following will happen while the cursor is in the headline:
  1316. - When the cursor is at the beginning of a headline, kill the entire
  1317. line and possible the folded subtree below the line.
  1318. - When in the middle of the headline text, kill the headline up to the tags.
  1319. - When after the headline text, kill the tags."
  1320. :group 'org-edit-structure
  1321. :type 'boolean)
  1322. (defcustom org-ctrl-k-protect-subtree nil
  1323. "Non-nil means, do not delete a hidden subtree with C-k.
  1324. When set to the symbol `error', simply throw an error when C-k is
  1325. used to kill (part-of) a headline that has hidden text behind it.
  1326. Any other non-nil value will result in a query to the user, if it is
  1327. OK to kill that hidden subtree. When nil, kill without remorse."
  1328. :group 'org-edit-structure
  1329. :version "24.1"
  1330. :type '(choice
  1331. (const :tag "Do not protect hidden subtrees" nil)
  1332. (const :tag "Protect hidden subtrees with a security query" t)
  1333. (const :tag "Never kill a hidden subtree with C-k" error)))
  1334. (defcustom org-special-ctrl-o t
  1335. "Non-nil means, make `C-o' insert a row in tables."
  1336. :group 'org-edit-structure
  1337. :type 'boolean)
  1338. (defcustom org-catch-invisible-edits nil
  1339. "Check if in invisible region before inserting or deleting a character.
  1340. Valid values are:
  1341. nil Do not check, so just do invisible edits.
  1342. error Throw an error and do nothing.
  1343. show Make point visible, and do the requested edit.
  1344. show-and-error Make point visible, then throw an error and abort the edit.
  1345. smart Make point visible, and do insertion/deletion if it is
  1346. adjacent to visible text and the change feels predictable.
  1347. Never delete a previously invisible character or add in the
  1348. middle or right after an invisible region. Basically, this
  1349. allows insertion and backward-delete right before ellipses.
  1350. FIXME: maybe in this case we should not even show?"
  1351. :group 'org-edit-structure
  1352. :version "24.1"
  1353. :type '(choice
  1354. (const :tag "Do not check" nil)
  1355. (const :tag "Throw error when trying to edit" error)
  1356. (const :tag "Unhide, but do not do the edit" show-and-error)
  1357. (const :tag "Show invisible part and do the edit" show)
  1358. (const :tag "Be smart and do the right thing" smart)))
  1359. (defcustom org-yank-folded-subtrees t
  1360. "Non-nil means when yanking subtrees, fold them.
  1361. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1362. it starts with a heading and all other headings in it are either children
  1363. or siblings, then fold all the subtrees. However, do this only if no
  1364. text after the yank would be swallowed into a folded tree by this action."
  1365. :group 'org-edit-structure
  1366. :type 'boolean)
  1367. (defcustom org-yank-adjusted-subtrees nil
  1368. "Non-nil means when yanking subtrees, adjust the level.
  1369. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1370. this function for details."
  1371. :group 'org-edit-structure
  1372. :type 'boolean)
  1373. (defcustom org-M-RET-may-split-line '((default . t))
  1374. "Non-nil means M-RET will split the line at the cursor position.
  1375. When nil, it will go to the end of the line before making a
  1376. new line.
  1377. You may also set this option in a different way for different
  1378. contexts. Valid contexts are:
  1379. headline when creating a new headline
  1380. item when creating a new item
  1381. table in a table field
  1382. default the value to be used for all contexts not explicitly
  1383. customized"
  1384. :group 'org-structure
  1385. :group 'org-table
  1386. :type '(choice
  1387. (const :tag "Always" t)
  1388. (const :tag "Never" nil)
  1389. (repeat :greedy t :tag "Individual contexts"
  1390. (cons
  1391. (choice :tag "Context"
  1392. (const headline)
  1393. (const item)
  1394. (const table)
  1395. (const default))
  1396. (boolean)))))
  1397. (defcustom org-insert-heading-respect-content nil
  1398. "Non-nil means insert new headings after the current subtree.
  1399. When nil, the new heading is created directly after the current line.
  1400. The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
  1401. this variable on for the duration of the command."
  1402. :group 'org-structure
  1403. :type 'boolean)
  1404. (defcustom org-blank-before-new-entry '((heading . auto)
  1405. (plain-list-item . auto))
  1406. "Should `org-insert-heading' leave a blank line before new heading/item?
  1407. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1408. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1409. which case Org will look at the surrounding headings/items and try to
  1410. make an intelligent decision whether to insert a blank line or not."
  1411. :group 'org-edit-structure
  1412. :type '(list
  1413. (cons (const heading)
  1414. (choice (const :tag "Never" nil)
  1415. (const :tag "Always" t)
  1416. (const :tag "Auto" auto)))
  1417. (cons (const plain-list-item)
  1418. (choice (const :tag "Never" nil)
  1419. (const :tag "Always" t)
  1420. (const :tag "Auto" auto)))))
  1421. (defcustom org-insert-heading-hook nil
  1422. "Hook being run after inserting a new heading."
  1423. :group 'org-edit-structure
  1424. :type 'hook)
  1425. (defcustom org-enable-fixed-width-editor t
  1426. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1427. This currently only means they are never auto-wrapped.
  1428. When nil, such lines will be treated like ordinary lines."
  1429. :group 'org-edit-structure
  1430. :type 'boolean)
  1431. (defcustom org-goto-auto-isearch t
  1432. "Non-nil means typing characters in `org-goto' starts incremental search.
  1433. When nil, you can use these keybindings to navigate the buffer:
  1434. q Quit the org-goto interface
  1435. n Go to the next visible heading
  1436. p Go to the previous visible heading
  1437. f Go one heading forward on same level
  1438. b Go one heading backward on same level
  1439. u Go one heading up"
  1440. :group 'org-edit-structure
  1441. :type 'boolean)
  1442. (defgroup org-sparse-trees nil
  1443. "Options concerning sparse trees in Org-mode."
  1444. :tag "Org Sparse Trees"
  1445. :group 'org-structure)
  1446. (defcustom org-highlight-sparse-tree-matches t
  1447. "Non-nil means highlight all matches that define a sparse tree.
  1448. The highlights will automatically disappear the next time the buffer is
  1449. changed by an edit command."
  1450. :group 'org-sparse-trees
  1451. :type 'boolean)
  1452. (defcustom org-remove-highlights-with-change t
  1453. "Non-nil means any change to the buffer will remove temporary highlights.
  1454. \\<org-mode-map>\
  1455. Such highlights are created by `org-occur' and `org-clock-display'.
  1456. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1457. to get rid of the highlights.
  1458. The highlights created by `org-toggle-latex-fragment' always need
  1459. `\\[org-toggle-latex-fragment]' to be removed."
  1460. :group 'org-sparse-trees
  1461. :group 'org-time
  1462. :type 'boolean)
  1463. (defcustom org-occur-hook '(org-first-headline-recenter)
  1464. "Hook that is run after `org-occur' has constructed a sparse tree.
  1465. This can be used to recenter the window to show as much of the structure
  1466. as possible."
  1467. :group 'org-sparse-trees
  1468. :type 'hook)
  1469. (defgroup org-imenu-and-speedbar nil
  1470. "Options concerning imenu and speedbar in Org-mode."
  1471. :tag "Org Imenu and Speedbar"
  1472. :group 'org-structure)
  1473. (defcustom org-imenu-depth 2
  1474. "The maximum level for Imenu access to Org-mode headlines.
  1475. This also applied for speedbar access."
  1476. :group 'org-imenu-and-speedbar
  1477. :type 'integer)
  1478. (defgroup org-table nil
  1479. "Options concerning tables in Org-mode."
  1480. :tag "Org Table"
  1481. :group 'org)
  1482. (defcustom org-enable-table-editor 'optimized
  1483. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1484. When nil, such lines will be treated like ordinary lines.
  1485. When equal to the symbol `optimized', the table editor will be optimized to
  1486. do the following:
  1487. - Automatic overwrite mode in front of whitespace in table fields.
  1488. This makes the structure of the table stay in tact as long as the edited
  1489. field does not exceed the column width.
  1490. - Minimize the number of realigns. Normally, the table is aligned each time
  1491. TAB or RET are pressed to move to another field. With optimization this
  1492. happens only if changes to a field might have changed the column width.
  1493. Optimization requires replacing the functions `self-insert-command',
  1494. `delete-char', and `backward-delete-char' in Org-mode buffers, with a
  1495. slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
  1496. very good at guessing when a re-align will be necessary, but you can always
  1497. force one with \\[org-ctrl-c-ctrl-c].
  1498. If you would like to use the optimized version in Org-mode, but the
  1499. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1500. This variable can be used to turn on and off the table editor during a session,
  1501. but in order to toggle optimization, a restart is required.
  1502. See also the variable `org-table-auto-blank-field'."
  1503. :group 'org-table
  1504. :type '(choice
  1505. (const :tag "off" nil)
  1506. (const :tag "on" t)
  1507. (const :tag "on, optimized" optimized)))
  1508. (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
  1509. (version<= emacs-version "24.1"))
  1510. "Non-nil means cluster self-insert commands for undo when possible.
  1511. If this is set, then, like in the Emacs command loop, 20 consecutive
  1512. characters will be undone together.
  1513. This is configurable, because there is some impact on typing performance."
  1514. :group 'org-table
  1515. :type 'boolean)
  1516. (defcustom org-table-tab-recognizes-table.el t
  1517. "Non-nil means TAB will automatically notice a table.el table.
  1518. When it sees such a table, it moves point into it and - if necessary -
  1519. calls `table-recognize-table'."
  1520. :group 'org-table-editing
  1521. :type 'boolean)
  1522. (defgroup org-link nil
  1523. "Options concerning links in Org-mode."
  1524. :tag "Org Link"
  1525. :group 'org)
  1526. (defvar-local org-link-abbrev-alist-local nil
  1527. "Buffer-local version of `org-link-abbrev-alist', which see.
  1528. The value of this is taken from the #+LINK lines.")
  1529. (defcustom org-link-abbrev-alist nil
  1530. "Alist of link abbreviations.
  1531. The car of each element is a string, to be replaced at the start of a link.
  1532. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1533. links in Org-mode buffers can have an optional tag after a double colon, e.g.
  1534. [[linkkey:tag][description]]
  1535. The `linkkey' must be a word word, starting with a letter, followed
  1536. by letters, numbers, `-' or `_'.
  1537. If REPLACE is a string, the tag will simply be appended to create the link.
  1538. If the string contains \"%s\", the tag will be inserted there. If the string
  1539. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1540. at that point (see the function `url-hexify-string'). If the string contains
  1541. the specifier \"%(my-function)\", then the custom function `my-function' will
  1542. be invoked: this function takes the tag as its only argument and must return
  1543. a string.
  1544. REPLACE may also be a function that will be called with the tag as the
  1545. only argument to create the link, which should be returned as a string.
  1546. See the manual for examples."
  1547. :group 'org-link
  1548. :type '(repeat
  1549. (cons
  1550. (string :tag "Protocol")
  1551. (choice
  1552. (string :tag "Format")
  1553. (function)))))
  1554. (defcustom org-descriptive-links t
  1555. "Non-nil means Org will display descriptive links.
  1556. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1557. \"Org Website\", hiding the link itself and just displaying its
  1558. description. When set to nil, Org will display the full links
  1559. literally.
  1560. You can interactively set the value of this variable by calling
  1561. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1562. :group 'org-link
  1563. :type 'boolean)
  1564. (defcustom org-link-file-path-type 'adaptive
  1565. "How the path name in file links should be stored.
  1566. Valid values are:
  1567. relative Relative to the current directory, i.e. the directory of the file
  1568. into which the link is being inserted.
  1569. absolute Absolute path, if possible with ~ for home directory.
  1570. noabbrev Absolute path, no abbreviation of home directory.
  1571. adaptive Use relative path for files in the current directory and sub-
  1572. directories of it. For other files, use an absolute path."
  1573. :group 'org-link
  1574. :type '(choice
  1575. (const relative)
  1576. (const absolute)
  1577. (const noabbrev)
  1578. (const adaptive)))
  1579. (defvaralias 'org-activate-links 'org-highlight-links)
  1580. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1581. "Types of links that should be highlighted in Org-mode files.
  1582. This is a list of symbols, each one of them leading to the
  1583. highlighting of a certain link type.
  1584. You can still open links that are not highlighted.
  1585. In principle, it does not hurt to turn on highlighting for all
  1586. link types. There may be a small gain when turning off unused
  1587. link types. The types are:
  1588. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1589. angle Links in angular brackets that may contain whitespace like
  1590. <bbdb:Carsten Dominik>.
  1591. plain Plain links in normal text, no whitespace, like http://google.com.
  1592. radio Text that is matched by a radio target, see manual for details.
  1593. tag Tag settings in a headline (link to tag search).
  1594. date Time stamps (link to calendar).
  1595. footnote Footnote labels.
  1596. If you set this variable during an Emacs session, use `org-mode-restart'
  1597. in the Org buffer so that the change takes effect."
  1598. :group 'org-link
  1599. :group 'org-appearance
  1600. :type '(set :greedy t
  1601. (const :tag "Double bracket links" bracket)
  1602. (const :tag "Angular bracket links" angle)
  1603. (const :tag "Plain text links" plain)
  1604. (const :tag "Radio target matches" radio)
  1605. (const :tag "Tags" tag)
  1606. (const :tag "Timestamps" date)
  1607. (const :tag "Footnotes" footnote)))
  1608. (defcustom org-make-link-description-function nil
  1609. "Function to use for generating link descriptions from links.
  1610. When nil, the link location will be used. This function must take
  1611. two parameters: the first one is the link, the second one is the
  1612. description generated by `org-insert-link'. The function should
  1613. return the description to use."
  1614. :group 'org-link
  1615. :type '(choice (const nil) (function)))
  1616. (defgroup org-link-store nil
  1617. "Options concerning storing links in Org-mode."
  1618. :tag "Org Store Link"
  1619. :group 'org-link)
  1620. (defcustom org-url-hexify-p t
  1621. "When non-nil, hexify URL when creating a link."
  1622. :type 'boolean
  1623. :version "24.3"
  1624. :group 'org-link-store)
  1625. (defcustom org-email-link-description-format "Email %c: %.30s"
  1626. "Format of the description part of a link to an email or usenet message.
  1627. The following %-escapes will be replaced by corresponding information:
  1628. %F full \"From\" field
  1629. %f name, taken from \"From\" field, address if no name
  1630. %T full \"To\" field
  1631. %t first name in \"To\" field, address if no name
  1632. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1633. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1634. %s subject
  1635. %d date
  1636. %m message-id.
  1637. You may use normal field width specification between the % and the letter.
  1638. This is for example useful to limit the length of the subject.
  1639. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1640. :group 'org-link-store
  1641. :type 'string)
  1642. (defcustom org-from-is-user-regexp
  1643. (let (r1 r2)
  1644. (when (and user-mail-address (not (string= user-mail-address "")))
  1645. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1646. (when (and user-full-name (not (string= user-full-name "")))
  1647. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1648. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1649. "Regexp matched against the \"From:\" header of an email or usenet message.
  1650. It should match if the message is from the user him/herself."
  1651. :group 'org-link-store
  1652. :type 'regexp)
  1653. (defcustom org-context-in-file-links t
  1654. "Non-nil means file links from `org-store-link' contain context.
  1655. A search string will be added to the file name with :: as separator and
  1656. used to find the context when the link is activated by the command
  1657. `org-open-at-point'. When this option is t, the entire active region
  1658. will be placed in the search string of the file link. If set to a
  1659. positive integer, only the first n lines of context will be stored.
  1660. Using a prefix arg to the command \\[org-store-link] (`org-store-link')
  1661. negates this setting for the duration of the command."
  1662. :group 'org-link-store
  1663. :type '(choice boolean integer))
  1664. (defcustom org-keep-stored-link-after-insertion nil
  1665. "Non-nil means keep link in list for entire session.
  1666. The command `org-store-link' adds a link pointing to the current
  1667. location to an internal list. These links accumulate during a session.
  1668. The command `org-insert-link' can be used to insert links into any
  1669. Org-mode file (offering completion for all stored links). When this
  1670. option is nil, every link which has been inserted once using \\[org-insert-link]
  1671. will be removed from the list, to make completing the unused links
  1672. more efficient."
  1673. :group 'org-link-store
  1674. :type 'boolean)
  1675. (defgroup org-link-follow nil
  1676. "Options concerning following links in Org-mode."
  1677. :tag "Org Follow Link"
  1678. :group 'org-link)
  1679. (defcustom org-link-translation-function nil
  1680. "Function to translate links with different syntax to Org syntax.
  1681. This can be used to translate links created for example by the Planner
  1682. or emacs-wiki packages to Org syntax.
  1683. The function must accept two parameters, a TYPE containing the link
  1684. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1685. which is everything after the link protocol. It should return a cons
  1686. with possibly modified values of type and path.
  1687. Org contains a function for this, so if you set this variable to
  1688. `org-translate-link-from-planner', you should be able follow many
  1689. links created by planner."
  1690. :group 'org-link-follow
  1691. :type '(choice (const nil) (function)))
  1692. (defcustom org-follow-link-hook nil
  1693. "Hook that is run after a link has been followed."
  1694. :group 'org-link-follow
  1695. :type 'hook)
  1696. (defcustom org-tab-follows-link nil
  1697. "Non-nil means on links TAB will follow the link.
  1698. Needs to be set before org.el is loaded.
  1699. This really should not be used, it does not make sense, and the
  1700. implementation is bad."
  1701. :group 'org-link-follow
  1702. :type 'boolean)
  1703. (defcustom org-return-follows-link nil
  1704. "Non-nil means on links RET will follow the link.
  1705. In tables, the special behavior of RET has precedence."
  1706. :group 'org-link-follow
  1707. :type 'boolean)
  1708. (defcustom org-mouse-1-follows-link
  1709. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1710. "Non-nil means mouse-1 on a link will follow the link.
  1711. A longer mouse click will still set point. Does not work on XEmacs.
  1712. Needs to be set before org.el is loaded."
  1713. :group 'org-link-follow
  1714. :version "24.4"
  1715. :package-version '(Org . "8.3")
  1716. :type '(choice
  1717. (const :tag "A double click follows the link" double)
  1718. (const :tag "Unconditionally follow the link with mouse-1" t)
  1719. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1720. (defcustom org-mark-ring-length 4
  1721. "Number of different positions to be recorded in the ring.
  1722. Changing this requires a restart of Emacs to work correctly."
  1723. :group 'org-link-follow
  1724. :type 'integer)
  1725. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1726. "Non-nil means internal links in Org files must exactly match a headline.
  1727. When nil, the link search tries to match a phrase with all words
  1728. in the search text."
  1729. :group 'org-link-follow
  1730. :version "24.1"
  1731. :type '(choice
  1732. (const :tag "Use fuzzy text search" nil)
  1733. (const :tag "Match only exact headline" t)
  1734. (const :tag "Match exact headline or query to create it"
  1735. query-to-create)))
  1736. (defcustom org-link-frame-setup
  1737. '((vm . vm-visit-folder-other-frame)
  1738. (vm-imap . vm-visit-imap-folder-other-frame)
  1739. (gnus . org-gnus-no-new-news)
  1740. (file . find-file-other-window)
  1741. (wl . wl-other-frame))
  1742. "Setup the frame configuration for following links.
  1743. When following a link with Emacs, it may often be useful to display
  1744. this link in another window or frame. This variable can be used to
  1745. set this up for the different types of links.
  1746. For VM, use any of
  1747. `vm-visit-folder'
  1748. `vm-visit-folder-other-window'
  1749. `vm-visit-folder-other-frame'
  1750. For Gnus, use any of
  1751. `gnus'
  1752. `gnus-other-frame'
  1753. `org-gnus-no-new-news'
  1754. For FILE, use any of
  1755. `find-file'
  1756. `find-file-other-window'
  1757. `find-file-other-frame'
  1758. For Wanderlust use any of
  1759. `wl'
  1760. `wl-other-frame'
  1761. For the calendar, use the variable `calendar-setup'.
  1762. For BBDB, it is currently only possible to display the matches in
  1763. another window."
  1764. :group 'org-link-follow
  1765. :type '(list
  1766. (cons (const vm)
  1767. (choice
  1768. (const vm-visit-folder)
  1769. (const vm-visit-folder-other-window)
  1770. (const vm-visit-folder-other-frame)))
  1771. (cons (const vm-imap)
  1772. (choice
  1773. (const vm-visit-imap-folder)
  1774. (const vm-visit-imap-folder-other-window)
  1775. (const vm-visit-imap-folder-other-frame)))
  1776. (cons (const gnus)
  1777. (choice
  1778. (const gnus)
  1779. (const gnus-other-frame)
  1780. (const org-gnus-no-new-news)))
  1781. (cons (const file)
  1782. (choice
  1783. (const find-file)
  1784. (const find-file-other-window)
  1785. (const find-file-other-frame)))
  1786. (cons (const wl)
  1787. (choice
  1788. (const wl)
  1789. (const wl-other-frame)))))
  1790. (defcustom org-display-internal-link-with-indirect-buffer nil
  1791. "Non-nil means use indirect buffer to display infile links.
  1792. Activating internal links (from one location in a file to another location
  1793. in the same file) normally just jumps to the location. When the link is
  1794. activated with a \\[universal-argument] prefix (or with mouse-3), the link \
  1795. is displayed in
  1796. another window. When this option is set, the other window actually displays
  1797. an indirect buffer clone of the current buffer, to avoid any visibility
  1798. changes to the current buffer."
  1799. :group 'org-link-follow
  1800. :type 'boolean)
  1801. (defcustom org-open-non-existing-files nil
  1802. "Non-nil means `org-open-file' will open non-existing files.
  1803. When nil, an error will be generated.
  1804. This variable applies only to external applications because they
  1805. might choke on non-existing files. If the link is to a file that
  1806. will be opened in Emacs, the variable is ignored."
  1807. :group 'org-link-follow
  1808. :type 'boolean)
  1809. (defcustom org-open-directory-means-index-dot-org nil
  1810. "Non-nil means a link to a directory really means to index.org.
  1811. When nil, following a directory link will run dired or open a finder/explorer
  1812. window on that directory."
  1813. :group 'org-link-follow
  1814. :type 'boolean)
  1815. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1816. "Non-nil means ask for confirmation before executing shell links.
  1817. Shell links can be dangerous: just think about a link
  1818. [[shell:rm -rf ~/*][Google Search]]
  1819. This link would show up in your Org-mode document as \"Google Search\",
  1820. but really it would remove your entire home directory.
  1821. Therefore we advise against setting this variable to nil.
  1822. Just change it to `y-or-n-p' if you want to confirm with a
  1823. single keystroke rather than having to type \"yes\"."
  1824. :group 'org-link-follow
  1825. :type '(choice
  1826. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1827. (const :tag "with y-or-n (faster)" y-or-n-p)
  1828. (const :tag "no confirmation (dangerous)" nil)))
  1829. (put 'org-confirm-shell-link-function
  1830. 'safe-local-variable
  1831. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1832. (defcustom org-confirm-shell-link-not-regexp ""
  1833. "A regexp to skip confirmation for shell links."
  1834. :group 'org-link-follow
  1835. :version "24.1"
  1836. :type 'regexp)
  1837. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1838. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1839. Elisp links can be dangerous: just think about a link
  1840. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1841. This link would show up in your Org-mode document as \"Google Search\",
  1842. but really it would remove your entire home directory.
  1843. Therefore we advise against setting this variable to nil.
  1844. Just change it to `y-or-n-p' if you want to confirm with a
  1845. single keystroke rather than having to type \"yes\"."
  1846. :group 'org-link-follow
  1847. :type '(choice
  1848. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1849. (const :tag "with y-or-n (faster)" y-or-n-p)
  1850. (const :tag "no confirmation (dangerous)" nil)))
  1851. (put 'org-confirm-shell-link-function
  1852. 'safe-local-variable
  1853. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1854. (defcustom org-confirm-elisp-link-not-regexp ""
  1855. "A regexp to skip confirmation for Elisp links."
  1856. :group 'org-link-follow
  1857. :version "24.1"
  1858. :type 'regexp)
  1859. (defconst org-file-apps-defaults-gnu
  1860. '((remote . emacs)
  1861. (system . mailcap)
  1862. (t . mailcap))
  1863. "Default file applications on a UNIX or GNU/Linux system.
  1864. See `org-file-apps'.")
  1865. (defconst org-file-apps-defaults-macosx
  1866. '((remote . emacs)
  1867. (t . "open %s")
  1868. (system . "open %s")
  1869. ("ps.gz" . "gv %s")
  1870. ("eps.gz" . "gv %s")
  1871. ("dvi" . "xdvi %s")
  1872. ("fig" . "xfig %s"))
  1873. "Default file applications on a MacOS X system.
  1874. The system \"open\" is known as a default, but we use X11 applications
  1875. for some files for which the OS does not have a good default.
  1876. See `org-file-apps'.")
  1877. (defconst org-file-apps-defaults-windowsnt
  1878. (list
  1879. '(remote . emacs)
  1880. (cons t
  1881. (list (if (featurep 'xemacs)
  1882. 'mswindows-shell-execute
  1883. 'w32-shell-execute)
  1884. "open" 'file))
  1885. (cons 'system
  1886. (list (if (featurep 'xemacs)
  1887. 'mswindows-shell-execute
  1888. 'w32-shell-execute)
  1889. "open" 'file)))
  1890. "Default file applications on a Windows NT system.
  1891. The system \"open\" is used for most files.
  1892. See `org-file-apps'.")
  1893. (defcustom org-file-apps
  1894. '((auto-mode . emacs)
  1895. ("\\.mm\\'" . default)
  1896. ("\\.x?html?\\'" . default)
  1897. ("\\.pdf\\'" . default))
  1898. "External applications for opening `file:path' items in a document.
  1899. Org-mode uses system defaults for different file types, but
  1900. you can use this variable to set the application for a given file
  1901. extension. The entries in this list are cons cells where the car identifies
  1902. files and the cdr the corresponding command. Possible values for the
  1903. file identifier are
  1904. \"string\" A string as a file identifier can be interpreted in different
  1905. ways, depending on its contents:
  1906. - Alphanumeric characters only:
  1907. Match links with this file extension.
  1908. Example: (\"pdf\" . \"evince %s\")
  1909. to open PDFs with evince.
  1910. - Regular expression: Match links where the
  1911. filename matches the regexp. If you want to
  1912. use groups here, use shy groups.
  1913. Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
  1914. (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
  1915. to open *.html and *.xhtml with firefox.
  1916. - Regular expression which contains (non-shy) groups:
  1917. Match links where the whole link, including \"::\", and
  1918. anything after that, matches the regexp.
  1919. In a custom command string, %1, %2, etc. are replaced with
  1920. the parts of the link that were matched by the groups.
  1921. For backwards compatibility, if a command string is given
  1922. that does not use any of the group matches, this case is
  1923. handled identically to the second one (i.e. match against
  1924. file name only).
  1925. In a custom lisp form, you can access the group matches with
  1926. (match-string n link).
  1927. Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
  1928. to open [[file:document.pdf::5]] with evince at page 5.
  1929. `directory' Matches a directory
  1930. `remote' Matches a remote file, accessible through tramp or efs.
  1931. Remote files most likely should be visited through Emacs
  1932. because external applications cannot handle such paths.
  1933. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1934. so all files Emacs knows how to handle. Using this with
  1935. command `emacs' will open most files in Emacs. Beware that this
  1936. will also open html files inside Emacs, unless you add
  1937. (\"html\" . default) to the list as well.
  1938. t Default for files not matched by any of the other options.
  1939. `system' The system command to open files, like `open' on Windows
  1940. and Mac OS X, and mailcap under GNU/Linux. This is the command
  1941. that will be selected if you call `C-c C-o' with a double
  1942. \\[universal-argument] \\[universal-argument] prefix.
  1943. Possible values for the command are:
  1944. `emacs' The file will be visited by the current Emacs process.
  1945. `default' Use the default application for this file type, which is the
  1946. association for t in the list, most likely in the system-specific
  1947. part.
  1948. This can be used to overrule an unwanted setting in the
  1949. system-specific variable.
  1950. `system' Use the system command for opening files, like \"open\".
  1951. This command is specified by the entry whose car is `system'.
  1952. Most likely, the system-specific version of this variable
  1953. does define this command, but you can overrule/replace it
  1954. here.
  1955. string A command to be executed by a shell; %s will be replaced
  1956. by the path to the file.
  1957. sexp A Lisp form which will be evaluated. The file path will
  1958. be available in the Lisp variable `file'.
  1959. For more examples, see the system specific constants
  1960. `org-file-apps-defaults-macosx'
  1961. `org-file-apps-defaults-windowsnt'
  1962. `org-file-apps-defaults-gnu'."
  1963. :group 'org-link-follow
  1964. :type '(repeat
  1965. (cons (choice :value ""
  1966. (string :tag "Extension")
  1967. (const :tag "System command to open files" system)
  1968. (const :tag "Default for unrecognized files" t)
  1969. (const :tag "Remote file" remote)
  1970. (const :tag "Links to a directory" directory)
  1971. (const :tag "Any files that have Emacs modes"
  1972. auto-mode))
  1973. (choice :value ""
  1974. (const :tag "Visit with Emacs" emacs)
  1975. (const :tag "Use default" default)
  1976. (const :tag "Use the system command" system)
  1977. (string :tag "Command")
  1978. (sexp :tag "Lisp form")))))
  1979. (defcustom org-doi-server-url "http://dx.doi.org/"
  1980. "The URL of the DOI server."
  1981. :type 'string
  1982. :version "24.3"
  1983. :group 'org-link-follow)
  1984. (defgroup org-refile nil
  1985. "Options concerning refiling entries in Org-mode."
  1986. :tag "Org Refile"
  1987. :group 'org)
  1988. (defcustom org-directory "~/org"
  1989. "Directory with org files.
  1990. This is just a default location to look for Org files. There is no need
  1991. at all to put your files into this directory. It is only used in the
  1992. following situations:
  1993. 1. When a capture template specifies a target file that is not an
  1994. absolute path. The path will then be interpreted relative to
  1995. `org-directory'
  1996. 2. When a capture note is filed away in an interactive way (when exiting the
  1997. note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
  1998. with `org-directory' as the default path."
  1999. :group 'org-refile
  2000. :group 'org-capture
  2001. :type 'directory)
  2002. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2003. "Default target for storing notes.
  2004. Used as a fall back file for org-capture.el, for templates that
  2005. do not specify a target file."
  2006. :group 'org-refile
  2007. :group 'org-capture
  2008. :type 'file)
  2009. (defcustom org-goto-interface 'outline
  2010. "The default interface to be used for `org-goto'.
  2011. Allowed values are:
  2012. outline The interface shows an outline of the relevant file
  2013. and the correct heading is found by moving through
  2014. the outline or by searching with incremental search.
  2015. outline-path-completion Headlines in the current buffer are offered via
  2016. completion. This is the interface also used by
  2017. the refile command."
  2018. :group 'org-refile
  2019. :type '(choice
  2020. (const :tag "Outline" outline)
  2021. (const :tag "Outline-path-completion" outline-path-completion)))
  2022. (defcustom org-goto-max-level 5
  2023. "Maximum target level when running `org-goto' with refile interface."
  2024. :group 'org-refile
  2025. :type 'integer)
  2026. (defcustom org-reverse-note-order nil
  2027. "Non-nil means store new notes at the beginning of a file or entry.
  2028. When nil, new notes will be filed to the end of a file or entry.
  2029. This can also be a list with cons cells of regular expressions that
  2030. are matched against file names, and values."
  2031. :group 'org-capture
  2032. :group 'org-refile
  2033. :type '(choice
  2034. (const :tag "Reverse always" t)
  2035. (const :tag "Reverse never" nil)
  2036. (repeat :tag "By file name regexp"
  2037. (cons regexp boolean))))
  2038. (defcustom org-log-refile nil
  2039. "Information to record when a task is refiled.
  2040. Possible values are:
  2041. nil Don't add anything
  2042. time Add a time stamp to the task
  2043. note Prompt for a note and add it with template `org-log-note-headings'
  2044. This option can also be set with on a per-file-basis with
  2045. #+STARTUP: nologrefile
  2046. #+STARTUP: logrefile
  2047. #+STARTUP: lognoterefile
  2048. You can have local logging settings for a subtree by setting the LOGGING
  2049. property to one or more of these keywords.
  2050. When bulk-refiling from the agenda, the value `note' is forbidden and
  2051. will temporarily be changed to `time'."
  2052. :group 'org-refile
  2053. :group 'org-progress
  2054. :version "24.1"
  2055. :type '(choice
  2056. (const :tag "No logging" nil)
  2057. (const :tag "Record timestamp" time)
  2058. (const :tag "Record timestamp with note." note)))
  2059. (defcustom org-refile-targets nil
  2060. "Targets for refiling entries with \\[org-refile].
  2061. This is a list of cons cells. Each cell contains:
  2062. - a specification of the files to be considered, either a list of files,
  2063. or a symbol whose function or variable value will be used to retrieve
  2064. a file name or a list of file names. If you use `org-agenda-files' for
  2065. that, all agenda files will be scanned for targets. Nil means consider
  2066. headings in the current buffer.
  2067. - A specification of how to find candidate refile targets. This may be
  2068. any of:
  2069. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2070. This tag has to be present in all target headlines, inheritance will
  2071. not be considered.
  2072. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2073. todo keyword.
  2074. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2075. headlines that are refiling targets.
  2076. - a cons cell (:level . N). Any headline of level N is considered a target.
  2077. Note that, when `org-odd-levels-only' is set, level corresponds to
  2078. order in hierarchy, not to the number of stars.
  2079. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2080. Note that, when `org-odd-levels-only' is set, level corresponds to
  2081. order in hierarchy, not to the number of stars.
  2082. Each element of this list generates a set of possible targets.
  2083. The union of these sets is presented (with completion) to
  2084. the user by `org-refile'.
  2085. You can set the variable `org-refile-target-verify-function' to a function
  2086. to verify each headline found by the simple criteria above.
  2087. When this variable is nil, all top-level headlines in the current buffer
  2088. are used, equivalent to the value `((nil . (:level . 1))'."
  2089. :group 'org-refile
  2090. :type '(repeat
  2091. (cons
  2092. (choice :value org-agenda-files
  2093. (const :tag "All agenda files" org-agenda-files)
  2094. (const :tag "Current buffer" nil)
  2095. (function) (variable) (file))
  2096. (choice :tag "Identify target headline by"
  2097. (cons :tag "Specific tag" (const :value :tag) (string))
  2098. (cons :tag "TODO keyword" (const :value :todo) (string))
  2099. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2100. (cons :tag "Level number" (const :value :level) (integer))
  2101. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2102. (defcustom org-refile-target-verify-function nil
  2103. "Function to verify if the headline at point should be a refile target.
  2104. The function will be called without arguments, with point at the
  2105. beginning of the headline. It should return t and leave point
  2106. where it is if the headline is a valid target for refiling.
  2107. If the target should not be selected, the function must return nil.
  2108. In addition to this, it may move point to a place from where the search
  2109. should be continued. For example, the function may decide that the entire
  2110. subtree of the current entry should be excluded and move point to the end
  2111. of the subtree."
  2112. :group 'org-refile
  2113. :type '(choice
  2114. (const nil)
  2115. (function)))
  2116. (defcustom org-refile-use-cache nil
  2117. "Non-nil means cache refile targets to speed up the process.
  2118. \\<org-mode-map>\
  2119. The cache for a particular file will be updated automatically when
  2120. the buffer has been killed, or when any of the marker used for flagging
  2121. refile targets no longer points at a live buffer.
  2122. If you have added new entries to a buffer that might themselves be targets,
  2123. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2124. if you find that easier, \
  2125. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2126. \\[org-refile]'."
  2127. :group 'org-refile
  2128. :version "24.1"
  2129. :type 'boolean)
  2130. (defcustom org-refile-use-outline-path nil
  2131. "Non-nil means provide refile targets as paths.
  2132. So a level 3 headline will be available as level1/level2/level3.
  2133. When the value is `file', also include the file name (without directory)
  2134. into the path. In this case, you can also stop the completion after
  2135. the file name, to get entries inserted as top level in the file.
  2136. When `full-file-path', include the full file path."
  2137. :group 'org-refile
  2138. :type '(choice
  2139. (const :tag "Not" nil)
  2140. (const :tag "Yes" t)
  2141. (const :tag "Start with file name" file)
  2142. (const :tag "Start with full file path" full-file-path)))
  2143. (defcustom org-outline-path-complete-in-steps t
  2144. "Non-nil means complete the outline path in hierarchical steps.
  2145. When Org-mode uses the refile interface to select an outline path
  2146. \(see variable `org-refile-use-outline-path'), the completion of
  2147. the path can be done in a single go, or it can be done in steps down
  2148. the headline hierarchy. Going in steps is probably the best if you
  2149. do not use a special completion package like `ido' or `icicles'.
  2150. However, when using these packages, going in one step can be very
  2151. fast, while still showing the whole path to the entry."
  2152. :group 'org-refile
  2153. :type 'boolean)
  2154. (defcustom org-refile-allow-creating-parent-nodes nil
  2155. "Non-nil means allow to create new nodes as refile targets.
  2156. New nodes are then created by adding \"/new node name\" to the completion
  2157. of an existing node. When the value of this variable is `confirm',
  2158. new node creation must be confirmed by the user (recommended).
  2159. When nil, the completion must match an existing entry.
  2160. Note that, if the new heading is not seen by the criteria
  2161. listed in `org-refile-targets', multiple instances of the same
  2162. heading would be created by trying again to file under the new
  2163. heading."
  2164. :group 'org-refile
  2165. :type '(choice
  2166. (const :tag "Never" nil)
  2167. (const :tag "Always" t)
  2168. (const :tag "Prompt for confirmation" confirm)))
  2169. (defcustom org-refile-active-region-within-subtree nil
  2170. "Non-nil means also refile active region within a subtree.
  2171. By default `org-refile' doesn't allow refiling regions if they
  2172. don't contain a set of subtrees, but it might be convenient to
  2173. do so sometimes: in that case, the first line of the region is
  2174. converted to a headline before refiling."
  2175. :group 'org-refile
  2176. :version "24.1"
  2177. :type 'boolean)
  2178. (defgroup org-todo nil
  2179. "Options concerning TODO items in Org-mode."
  2180. :tag "Org TODO"
  2181. :group 'org)
  2182. (defgroup org-progress nil
  2183. "Options concerning Progress logging in Org-mode."
  2184. :tag "Org Progress"
  2185. :group 'org-time)
  2186. (defvar org-todo-interpretation-widgets
  2187. '((:tag "Sequence (cycling hits every state)" sequence)
  2188. (:tag "Type (cycling directly to DONE)" type))
  2189. "The available interpretation symbols for customizing `org-todo-keywords'.
  2190. Interested libraries should add to this list.")
  2191. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2192. "List of TODO entry keyword sequences and their interpretation.
  2193. \\<org-mode-map>This is a list of sequences.
  2194. Each sequence starts with a symbol, either `sequence' or `type',
  2195. indicating if the keywords should be interpreted as a sequence of
  2196. action steps, or as different types of TODO items. The first
  2197. keywords are states requiring action - these states will select a headline
  2198. for inclusion into the global TODO list Org-mode produces. If one of
  2199. the \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2200. signify that no further action is necessary. If \"|\" is not found,
  2201. the last keyword is treated as the only DONE state of the sequence.
  2202. The command \\[org-todo] cycles an entry through these states, and one
  2203. additional state where no keyword is present. For details about this
  2204. cycling, see the manual.
  2205. TODO keywords and interpretation can also be set on a per-file basis with
  2206. the special #+SEQ_TODO and #+TYP_TODO lines.
  2207. Each keyword can optionally specify a character for fast state selection
  2208. \(in combination with the variable `org-use-fast-todo-selection')
  2209. and specifiers for state change logging, using the same syntax that
  2210. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2211. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2212. indicates to record a time stamp each time this state is selected.
  2213. Each keyword may also specify if a timestamp or a note should be
  2214. recorded when entering or leaving the state, by adding additional
  2215. characters in the parenthesis after the keyword. This looks like this:
  2216. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2217. record only the time of the state change. With X and Y being either
  2218. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2219. Y when leaving the state if and only if the *target* state does not
  2220. define X. You may omit any of the fast-selection key or X or /Y,
  2221. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2222. For backward compatibility, this variable may also be just a list
  2223. of keywords. In this case the interpretation (sequence or type) will be
  2224. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2225. :group 'org-todo
  2226. :group 'org-keywords
  2227. :type '(choice
  2228. (repeat :tag "Old syntax, just keywords"
  2229. (string :tag "Keyword"))
  2230. (repeat :tag "New syntax"
  2231. (cons
  2232. (choice
  2233. :tag "Interpretation"
  2234. ;;Quick and dirty way to see
  2235. ;;`org-todo-interpretations'. This takes the
  2236. ;;place of item arguments
  2237. :convert-widget
  2238. (lambda (widget)
  2239. (widget-put widget
  2240. :args (mapcar
  2241. (lambda (x)
  2242. (widget-convert
  2243. (cons 'const x)))
  2244. org-todo-interpretation-widgets))
  2245. widget))
  2246. (repeat
  2247. (string :tag "Keyword"))))))
  2248. (defvar-local org-todo-keywords-1 nil
  2249. "All TODO and DONE keywords active in a buffer.")
  2250. (defvar org-todo-keywords-for-agenda nil)
  2251. (defvar org-done-keywords-for-agenda nil)
  2252. (defvar org-todo-keyword-alist-for-agenda nil)
  2253. (defvar org-tag-alist-for-agenda nil
  2254. "Alist of all tags from all agenda files.")
  2255. (defvar org-tag-groups-alist-for-agenda nil
  2256. "Alist of all groups tags from all current agenda files.")
  2257. (defvar-local org-tag-groups-alist nil)
  2258. (defvar org-agenda-contributing-files nil)
  2259. (defvar-local org-not-done-keywords nil)
  2260. (defvar-local org-done-keywords nil)
  2261. (defvar-local org-todo-heads nil)
  2262. (defvar-local org-todo-sets nil)
  2263. (defvar-local org-todo-log-states nil)
  2264. (defvar-local org-todo-kwd-alist nil)
  2265. (defvar-local org-todo-key-alist nil)
  2266. (defvar-local org-todo-key-trigger nil)
  2267. (defcustom org-todo-interpretation 'sequence
  2268. "Controls how TODO keywords are interpreted.
  2269. This variable is in principle obsolete and is only used for
  2270. backward compatibility, if the interpretation of todo keywords is
  2271. not given already in `org-todo-keywords'. See that variable for
  2272. more information."
  2273. :group 'org-todo
  2274. :group 'org-keywords
  2275. :type '(choice (const sequence)
  2276. (const type)))
  2277. (defcustom org-use-fast-todo-selection t
  2278. "\\<org-mode-map>\
  2279. Non-nil means use the fast todo selection scheme with \\[org-todo].
  2280. This variable describes if and under what circumstances the cycling
  2281. mechanism for TODO keywords will be replaced by a single-key, direct
  2282. selection scheme.
  2283. When nil, fast selection is never used.
  2284. When the symbol `prefix', it will be used when `org-todo' is called
  2285. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2286. in an Org-mode buffer, and
  2287. `\\[universal-argument] t' in an agenda buffer.
  2288. When t, fast selection is used by default. In this case, the prefix
  2289. argument forces cycling instead.
  2290. In all cases, the special interface is only used if access keys have
  2291. actually been assigned by the user, i.e. if keywords in the configuration
  2292. are followed by a letter in parenthesis, like TODO(t)."
  2293. :group 'org-todo
  2294. :type '(choice
  2295. (const :tag "Never" nil)
  2296. (const :tag "By default" t)
  2297. (const :tag "Only with C-u C-c C-t" prefix)))
  2298. (defcustom org-provide-todo-statistics t
  2299. "Non-nil means update todo statistics after insert and toggle.
  2300. ALL-HEADLINES means update todo statistics by including headlines
  2301. with no TODO keyword as well, counting them as not done.
  2302. A list of TODO keywords means the same, but skip keywords that are
  2303. not in this list.
  2304. When set to a list of two lists, the first list contains keywords
  2305. to consider as TODO keywords, the second list contains keywords
  2306. to consider as DONE keywords.
  2307. When this is set, todo statistics is updated in the parent of the
  2308. current entry each time a todo state is changed."
  2309. :group 'org-todo
  2310. :type '(choice
  2311. (const :tag "Yes, only for TODO entries" t)
  2312. (const :tag "Yes, including all entries" all-headlines)
  2313. (repeat :tag "Yes, for TODOs in this list"
  2314. (string :tag "TODO keyword"))
  2315. (list :tag "Yes, for TODOs and DONEs in these lists"
  2316. (repeat (string :tag "TODO keyword"))
  2317. (repeat (string :tag "DONE keyword")))
  2318. (other :tag "No TODO statistics" nil)))
  2319. (defcustom org-hierarchical-todo-statistics t
  2320. "Non-nil means TODO statistics covers just direct children.
  2321. When nil, all entries in the subtree are considered.
  2322. This has only an effect if `org-provide-todo-statistics' is set.
  2323. To set this to nil for only a single subtree, use a COOKIE_DATA
  2324. property and include the word \"recursive\" into the value."
  2325. :group 'org-todo
  2326. :type 'boolean)
  2327. (defcustom org-after-todo-state-change-hook nil
  2328. "Hook which is run after the state of a TODO item was changed.
  2329. The new state (a string with a TODO keyword, or nil) is available in the
  2330. Lisp variable `org-state'."
  2331. :group 'org-todo
  2332. :type 'hook)
  2333. (defvar org-blocker-hook nil
  2334. "Hook for functions that are allowed to block a state change.
  2335. Functions in this hook should not modify the buffer.
  2336. Each function gets as its single argument a property list,
  2337. see `org-trigger-hook' for more information about this list.
  2338. If any of the functions in this hook returns nil, the state change
  2339. is blocked.")
  2340. (defvar org-trigger-hook nil
  2341. "Hook for functions that are triggered by a state change.
  2342. Each function gets as its single argument a property list with at
  2343. least the following elements:
  2344. (:type type-of-change :position pos-at-entry-start
  2345. :from old-state :to new-state)
  2346. Depending on the type, more properties may be present.
  2347. This mechanism is currently implemented for:
  2348. TODO state changes
  2349. ------------------
  2350. :type todo-state-change
  2351. :from previous state (keyword as a string), or nil, or a symbol
  2352. `todo' or `done', to indicate the general type of state.
  2353. :to new state, like in :from")
  2354. (defcustom org-enforce-todo-dependencies nil
  2355. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2356. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2357. be blocked if any prior sibling is not yet done.
  2358. Finally, if the parent is blocked because of ordered siblings of its own,
  2359. the child will also be blocked."
  2360. :set (lambda (var val)
  2361. (set var val)
  2362. (if val
  2363. (add-hook 'org-blocker-hook
  2364. 'org-block-todo-from-children-or-siblings-or-parent)
  2365. (remove-hook 'org-blocker-hook
  2366. 'org-block-todo-from-children-or-siblings-or-parent)))
  2367. :group 'org-todo
  2368. :type 'boolean)
  2369. (defcustom org-enforce-todo-checkbox-dependencies nil
  2370. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2371. When this is nil, checkboxes have no influence on switching TODO states.
  2372. When non-nil, you first need to check off all check boxes before the TODO
  2373. entry can be switched to DONE.
  2374. This variable needs to be set before org.el is loaded, and you need to
  2375. restart Emacs after a change to make the change effective. The only way
  2376. to change is while Emacs is running is through the customize interface."
  2377. :set (lambda (var val)
  2378. (set var val)
  2379. (if val
  2380. (add-hook 'org-blocker-hook
  2381. 'org-block-todo-from-checkboxes)
  2382. (remove-hook 'org-blocker-hook
  2383. 'org-block-todo-from-checkboxes)))
  2384. :group 'org-todo
  2385. :type 'boolean)
  2386. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2387. "Non-nil means inserting a TODO heading is treated as state change.
  2388. So when the command \\[org-insert-todo-heading] is used, state change
  2389. logging will apply if appropriate. When nil, the new TODO item will
  2390. be inserted directly, and no logging will take place."
  2391. :group 'org-todo
  2392. :type 'boolean)
  2393. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2394. "Non-nil means switching TODO states with S-cursor counts as state change.
  2395. This is the default behavior. However, setting this to nil allows a
  2396. convenient way to select a TODO state and bypass any logging associated
  2397. with that."
  2398. :group 'org-todo
  2399. :type 'boolean)
  2400. (defcustom org-todo-state-tags-triggers nil
  2401. "Tag changes that should be triggered by TODO state changes.
  2402. This is a list. Each entry is
  2403. (state-change (tag . flag) .......)
  2404. State-change can be a string with a state, and empty string to indicate the
  2405. state that has no TODO keyword, or it can be one of the symbols `todo'
  2406. or `done', meaning any not-done or done state, respectively."
  2407. :group 'org-todo
  2408. :group 'org-tags
  2409. :type '(repeat
  2410. (cons (choice :tag "When changing to"
  2411. (const :tag "Not-done state" todo)
  2412. (const :tag "Done state" done)
  2413. (string :tag "State"))
  2414. (repeat
  2415. (cons :tag "Tag action"
  2416. (string :tag "Tag")
  2417. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2418. (defcustom org-log-done nil
  2419. "Information to record when a task moves to the DONE state.
  2420. Possible values are:
  2421. nil Don't add anything, just change the keyword
  2422. time Add a time stamp to the task
  2423. note Prompt for a note and add it with template `org-log-note-headings'
  2424. This option can also be set with on a per-file-basis with
  2425. #+STARTUP: nologdone
  2426. #+STARTUP: logdone
  2427. #+STARTUP: lognotedone
  2428. You can have local logging settings for a subtree by setting the LOGGING
  2429. property to one or more of these keywords."
  2430. :group 'org-todo
  2431. :group 'org-progress
  2432. :type '(choice
  2433. (const :tag "No logging" nil)
  2434. (const :tag "Record CLOSED timestamp" time)
  2435. (const :tag "Record CLOSED timestamp with note." note)))
  2436. ;; Normalize old uses of org-log-done.
  2437. (cond
  2438. ((eq org-log-done t) (setq org-log-done 'time))
  2439. ((and (listp org-log-done) (memq 'done org-log-done))
  2440. (setq org-log-done 'note)))
  2441. (defcustom org-log-reschedule nil
  2442. "Information to record when the scheduling date of a tasks is modified.
  2443. Possible values are:
  2444. nil Don't add anything, just change the date
  2445. time Add a time stamp to the task
  2446. note Prompt for a note and add it with template `org-log-note-headings'
  2447. This option can also be set with on a per-file-basis with
  2448. #+STARTUP: nologreschedule
  2449. #+STARTUP: logreschedule
  2450. #+STARTUP: lognotereschedule"
  2451. :group 'org-todo
  2452. :group 'org-progress
  2453. :type '(choice
  2454. (const :tag "No logging" nil)
  2455. (const :tag "Record timestamp" time)
  2456. (const :tag "Record timestamp with note." note)))
  2457. (defcustom org-log-redeadline nil
  2458. "Information to record when the deadline date of a tasks is modified.
  2459. Possible values are:
  2460. nil Don't add anything, just change the date
  2461. time Add a time stamp to the task
  2462. note Prompt for a note and add it with template `org-log-note-headings'
  2463. This option can also be set with on a per-file-basis with
  2464. #+STARTUP: nologredeadline
  2465. #+STARTUP: logredeadline
  2466. #+STARTUP: lognoteredeadline
  2467. You can have local logging settings for a subtree by setting the LOGGING
  2468. property to one or more of these keywords."
  2469. :group 'org-todo
  2470. :group 'org-progress
  2471. :type '(choice
  2472. (const :tag "No logging" nil)
  2473. (const :tag "Record timestamp" time)
  2474. (const :tag "Record timestamp with note." note)))
  2475. (defcustom org-log-note-clock-out nil
  2476. "Non-nil means record a note when clocking out of an item.
  2477. This can also be configured on a per-file basis by adding one of
  2478. the following lines anywhere in the buffer:
  2479. #+STARTUP: lognoteclock-out
  2480. #+STARTUP: nolognoteclock-out"
  2481. :group 'org-todo
  2482. :group 'org-progress
  2483. :type 'boolean)
  2484. (defcustom org-log-done-with-time t
  2485. "Non-nil means the CLOSED time stamp will contain date and time.
  2486. When nil, only the date will be recorded."
  2487. :group 'org-progress
  2488. :type 'boolean)
  2489. (defcustom org-log-note-headings
  2490. '((done . "CLOSING NOTE %t")
  2491. (state . "State %-12s from %-12S %t")
  2492. (note . "Note taken on %t")
  2493. (reschedule . "Rescheduled from %S on %t")
  2494. (delschedule . "Not scheduled, was %S on %t")
  2495. (redeadline . "New deadline from %S on %t")
  2496. (deldeadline . "Removed deadline, was %S on %t")
  2497. (refile . "Refiled on %t")
  2498. (clock-out . ""))
  2499. "Headings for notes added to entries.
  2500. The value is an alist, with the car being a symbol indicating the
  2501. note context, and the cdr is the heading to be used. The heading
  2502. may also be the empty string. The following placeholders can be
  2503. used:
  2504. %t a time stamp.
  2505. %T an active time stamp instead the default inactive one
  2506. %d a short-format time stamp.
  2507. %D an active short-format time stamp.
  2508. %s the new TODO state or time stamp (inactive), in double quotes.
  2509. %S the old TODO state or time stamp (inactive), in double quotes.
  2510. %u the user name.
  2511. %U full user name.
  2512. In fact, it is not a good idea to change the `state' entry,
  2513. because Agenda Log mode depends on the format of these entries."
  2514. :group 'org-todo
  2515. :group 'org-progress
  2516. :type '(list :greedy t
  2517. (cons (const :tag "Heading when closing an item" done) string)
  2518. (cons (const :tag
  2519. "Heading when changing todo state (todo sequence only)"
  2520. state) string)
  2521. (cons (const :tag "Heading when just taking a note" note) string)
  2522. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2523. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2524. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2525. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2526. (cons (const :tag "Heading when refiling" refile) string)
  2527. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2528. (unless (assq 'note org-log-note-headings)
  2529. (push '(note . "%t") org-log-note-headings))
  2530. (defcustom org-log-into-drawer nil
  2531. "Non-nil means insert state change notes and time stamps into a drawer.
  2532. When nil, state changes notes will be inserted after the headline and
  2533. any scheduling and clock lines, but not inside a drawer.
  2534. The value of this variable should be the name of the drawer to use.
  2535. LOGBOOK is proposed as the default drawer for this purpose, you can
  2536. also set this to a string to define the drawer of your choice.
  2537. A value of t is also allowed, representing \"LOGBOOK\".
  2538. A value of t or nil can also be set with on a per-file-basis with
  2539. #+STARTUP: logdrawer
  2540. #+STARTUP: nologdrawer
  2541. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2542. will be ignored.
  2543. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2544. a subtree.
  2545. Do not check directly this variable in a Lisp program. Call
  2546. function `org-log-into-drawer' instead."
  2547. :group 'org-todo
  2548. :group 'org-progress
  2549. :type '(choice
  2550. (const :tag "Not into a drawer" nil)
  2551. (const :tag "LOGBOOK" t)
  2552. (string :tag "Other")))
  2553. (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2554. (defun org-log-into-drawer ()
  2555. "Name of the log drawer, as a string, or nil.
  2556. This is the value of `org-log-into-drawer'. However, if the
  2557. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2558. be used instead of the default value."
  2559. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2560. (cond ((equal p "nil") nil)
  2561. ((equal p "t") "LOGBOOK")
  2562. ((stringp p) p)
  2563. (p "LOGBOOK")
  2564. ((stringp org-log-into-drawer) org-log-into-drawer)
  2565. (org-log-into-drawer "LOGBOOK"))))
  2566. (defcustom org-log-state-notes-insert-after-drawers nil
  2567. "Non-nil means insert state change notes after any drawers in entry.
  2568. Only the drawers that *immediately* follow the headline and the
  2569. deadline/scheduled line are skipped.
  2570. When nil, insert notes right after the heading and perhaps the line
  2571. with deadline/scheduling if present.
  2572. This variable will have no effect if `org-log-into-drawer' is
  2573. set."
  2574. :group 'org-todo
  2575. :group 'org-progress
  2576. :type 'boolean)
  2577. (defcustom org-log-states-order-reversed t
  2578. "Non-nil means the latest state note will be directly after heading.
  2579. When nil, the state change notes will be ordered according to time.
  2580. This option can also be set with on a per-file-basis with
  2581. #+STARTUP: logstatesreversed
  2582. #+STARTUP: nologstatesreversed"
  2583. :group 'org-todo
  2584. :group 'org-progress
  2585. :type 'boolean)
  2586. (defcustom org-todo-repeat-to-state nil
  2587. "The TODO state to which a repeater should return the repeating task.
  2588. By default this is the first task in a TODO sequence, or the previous state
  2589. in a TODO_TYP set. But you can specify another task here.
  2590. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2591. :group 'org-todo
  2592. :version "24.1"
  2593. :type '(choice (const :tag "Head of sequence" nil)
  2594. (string :tag "Specific state")))
  2595. (defcustom org-log-repeat 'time
  2596. "Non-nil means record moving through the DONE state when triggering repeat.
  2597. An auto-repeating task is immediately switched back to TODO when
  2598. marked DONE. If you are not logging state changes (by adding \"@\"
  2599. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2600. record a closing note, there will be no record of the task moving
  2601. through DONE. This variable forces taking a note anyway.
  2602. nil Don't force a record
  2603. time Record a time stamp
  2604. note Prompt for a note and add it with template `org-log-note-headings'
  2605. This option can also be set with on a per-file-basis with
  2606. #+STARTUP: nologrepeat
  2607. #+STARTUP: logrepeat
  2608. #+STARTUP: lognoterepeat
  2609. You can have local logging settings for a subtree by setting the LOGGING
  2610. property to one or more of these keywords."
  2611. :group 'org-todo
  2612. :group 'org-progress
  2613. :type '(choice
  2614. (const :tag "Don't force a record" nil)
  2615. (const :tag "Force recording the DONE state" time)
  2616. (const :tag "Force recording a note with the DONE state" note)))
  2617. (defgroup org-priorities nil
  2618. "Priorities in Org-mode."
  2619. :tag "Org Priorities"
  2620. :group 'org-todo)
  2621. (defcustom org-enable-priority-commands t
  2622. "Non-nil means priority commands are active.
  2623. When nil, these commands will be disabled, so that you never accidentally
  2624. set a priority."
  2625. :group 'org-priorities
  2626. :type 'boolean)
  2627. (defcustom org-highest-priority ?A
  2628. "The highest priority of TODO items. A character like ?A, ?B etc.
  2629. Must have a smaller ASCII number than `org-lowest-priority'."
  2630. :group 'org-priorities
  2631. :type 'character)
  2632. (defcustom org-lowest-priority ?C
  2633. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2634. Must have a larger ASCII number than `org-highest-priority'."
  2635. :group 'org-priorities
  2636. :type 'character)
  2637. (defcustom org-default-priority ?B
  2638. "The default priority of TODO items.
  2639. This is the priority an item gets if no explicit priority is given.
  2640. When starting to cycle on an empty priority the first step in the cycle
  2641. depends on `org-priority-start-cycle-with-default'. The resulting first
  2642. step priority must not exceed the range from `org-highest-priority' to
  2643. `org-lowest-priority' which means that `org-default-priority' has to be
  2644. in this range exclusive or inclusive the range boundaries. Else the
  2645. first step refuses to set the default and the second will fall back
  2646. to (depending on the command used) the highest or lowest priority."
  2647. :group 'org-priorities
  2648. :type 'character)
  2649. (defcustom org-priority-start-cycle-with-default t
  2650. "Non-nil means start with default priority when starting to cycle.
  2651. When this is nil, the first step in the cycle will be (depending on the
  2652. command used) one higher or lower than the default priority.
  2653. See also `org-default-priority'."
  2654. :group 'org-priorities
  2655. :type 'boolean)
  2656. (defcustom org-get-priority-function nil
  2657. "Function to extract the priority from a string.
  2658. The string is normally the headline. If this is nil Org computes the
  2659. priority from the priority cookie like [#A] in the headline. It returns
  2660. an integer, increasing by 1000 for each priority level.
  2661. The user can set a different function here, which should take a string
  2662. as an argument and return the numeric priority."
  2663. :group 'org-priorities
  2664. :version "24.1"
  2665. :type '(choice
  2666. (const nil)
  2667. (function)))
  2668. (defgroup org-time nil
  2669. "Options concerning time stamps and deadlines in Org-mode."
  2670. :tag "Org Time"
  2671. :group 'org)
  2672. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2673. "Number of minutes to round time stamps to.
  2674. \\<org-mode-map>\
  2675. These are two values, the first applies when first creating a time stamp.
  2676. The second applies when changing it with the commands `S-up' and `S-down'.
  2677. When changing the time stamp, this means that it will change in steps
  2678. of N minutes, as given by the second value.
  2679. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2680. numbers should be factors of 60, so for example 5, 10, 15.
  2681. When this is larger than 1, you can still force an exact time stamp by using
  2682. a double prefix argument to a time stamp command like \
  2683. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2684. and by using a prefix arg to `S-up/down' to specify the exact number
  2685. of minutes to shift."
  2686. :group 'org-time
  2687. :get (lambda (var) ; Make sure both elements are there
  2688. (if (integerp (default-value var))
  2689. (list (default-value var) 5)
  2690. (default-value var)))
  2691. :type '(list
  2692. (integer :tag "when inserting times")
  2693. (integer :tag "when modifying times")))
  2694. ;; Normalize old customizations of this variable.
  2695. (when (integerp org-time-stamp-rounding-minutes)
  2696. (setq org-time-stamp-rounding-minutes
  2697. (list org-time-stamp-rounding-minutes
  2698. org-time-stamp-rounding-minutes)))
  2699. (defcustom org-display-custom-times nil
  2700. "Non-nil means overlay custom formats over all time stamps.
  2701. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2702. To turn this on on a per-file basis, insert anywhere in the file:
  2703. #+STARTUP: customtime"
  2704. :group 'org-time
  2705. :set 'set-default
  2706. :type 'sexp)
  2707. (make-variable-buffer-local 'org-display-custom-times)
  2708. (defcustom org-time-stamp-custom-formats
  2709. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2710. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2711. These are overlaid over the default ISO format if the variable
  2712. `org-display-custom-times' is set. Time like %H:%M should be at the
  2713. end of the second format. The custom formats are also honored by export
  2714. commands, if custom time display is turned on at the time of export."
  2715. :group 'org-time
  2716. :type 'sexp)
  2717. (defun org-time-stamp-format (&optional long inactive)
  2718. "Get the right format for a time string."
  2719. (let ((f (if long (cdr org-time-stamp-formats)
  2720. (car org-time-stamp-formats))))
  2721. (if inactive
  2722. (concat "[" (substring f 1 -1) "]")
  2723. f)))
  2724. (defcustom org-time-clocksum-format
  2725. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2726. "The format string used when creating CLOCKSUM lines.
  2727. This is also used when Org mode generates a time duration.
  2728. The value can be a single format string containing two
  2729. %-sequences, which will be filled with the number of hours and
  2730. minutes in that order.
  2731. Alternatively, the value can be a plist associating any of the
  2732. keys :years, :months, :weeks, :days, :hours or :minutes with
  2733. format strings. The time duration is formatted using only the
  2734. time components that are needed and concatenating the results.
  2735. If a time unit in absent, it falls back to the next smallest
  2736. unit.
  2737. The keys :require-years, :require-months, :require-days,
  2738. :require-weeks, :require-hours, :require-minutes are also
  2739. meaningful. A non-nil value for these keys indicates that the
  2740. corresponding time component should always be included, even if
  2741. its value is 0.
  2742. For example,
  2743. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2744. :require-minutes t)
  2745. means durations longer than a day will be expressed in days,
  2746. hours and minutes, and durations less than a day will always be
  2747. expressed in hours and minutes (even for durations less than an
  2748. hour).
  2749. The value
  2750. (:days \"%dd\" :minutes \"%dm\")
  2751. means durations longer than a day will be expressed in days and
  2752. minutes, and durations less than a day will be expressed entirely
  2753. in minutes (even for durations longer than an hour)."
  2754. :group 'org-time
  2755. :group 'org-clock
  2756. :version "24.4"
  2757. :package-version '(Org . "8.0")
  2758. :type '(choice (string :tag "Format string")
  2759. (set :tag "Plist"
  2760. (group :inline t (const :tag "Years" :years)
  2761. (string :tag "Format string"))
  2762. (group :inline t
  2763. (const :tag "Always show years" :require-years)
  2764. (const t))
  2765. (group :inline t (const :tag "Months" :months)
  2766. (string :tag "Format string"))
  2767. (group :inline t
  2768. (const :tag "Always show months" :require-months)
  2769. (const t))
  2770. (group :inline t (const :tag "Weeks" :weeks)
  2771. (string :tag "Format string"))
  2772. (group :inline t
  2773. (const :tag "Always show weeks" :require-weeks)
  2774. (const t))
  2775. (group :inline t (const :tag "Days" :days)
  2776. (string :tag "Format string"))
  2777. (group :inline t
  2778. (const :tag "Always show days" :require-days)
  2779. (const t))
  2780. (group :inline t (const :tag "Hours" :hours)
  2781. (string :tag "Format string"))
  2782. (group :inline t
  2783. (const :tag "Always show hours" :require-hours)
  2784. (const t))
  2785. (group :inline t (const :tag "Minutes" :minutes)
  2786. (string :tag "Format string"))
  2787. (group :inline t
  2788. (const :tag "Always show minutes" :require-minutes)
  2789. (const t)))))
  2790. (defcustom org-time-clocksum-use-fractional nil
  2791. "When non-nil, \\[org-clock-display] uses fractional times.
  2792. See `org-time-clocksum-format' for more on time clock formats."
  2793. :group 'org-time
  2794. :group 'org-clock
  2795. :version "24.3"
  2796. :type 'boolean)
  2797. (defcustom org-time-clocksum-use-effort-durations nil
  2798. "When non-nil, \\[org-clock-display] uses effort durations.
  2799. E.g. by default, one day is considered to be a 8 hours effort,
  2800. so a task that has been clocked for 16 hours will be displayed
  2801. as during 2 days in the clock display or in the clocktable.
  2802. See `org-effort-durations' on how to set effort durations
  2803. and `org-time-clocksum-format' for more on time clock formats."
  2804. :group 'org-time
  2805. :group 'org-clock
  2806. :version "24.4"
  2807. :package-version '(Org . "8.0")
  2808. :type 'boolean)
  2809. (defcustom org-time-clocksum-fractional-format "%.2f"
  2810. "The format string used when creating CLOCKSUM lines,
  2811. or when Org mode generates a time duration, if
  2812. `org-time-clocksum-use-fractional' is enabled.
  2813. The value can be a single format string containing one
  2814. %-sequence, which will be filled with the number of hours as
  2815. a float.
  2816. Alternatively, the value can be a plist associating any of the
  2817. keys :years, :months, :weeks, :days, :hours or :minutes with
  2818. a format string. The time duration is formatted using the
  2819. largest time unit which gives a non-zero integer part. If all
  2820. specified formats have zero integer part, the smallest time unit
  2821. is used."
  2822. :group 'org-time
  2823. :type '(choice (string :tag "Format string")
  2824. (set (group :inline t (const :tag "Years" :years)
  2825. (string :tag "Format string"))
  2826. (group :inline t (const :tag "Months" :months)
  2827. (string :tag "Format string"))
  2828. (group :inline t (const :tag "Weeks" :weeks)
  2829. (string :tag "Format string"))
  2830. (group :inline t (const :tag "Days" :days)
  2831. (string :tag "Format string"))
  2832. (group :inline t (const :tag "Hours" :hours)
  2833. (string :tag "Format string"))
  2834. (group :inline t (const :tag "Minutes" :minutes)
  2835. (string :tag "Format string")))))
  2836. (defcustom org-deadline-warning-days 14
  2837. "Number of days before expiration during which a deadline becomes active.
  2838. This variable governs the display in sparse trees and in the agenda.
  2839. When 0 or negative, it means use this number (the absolute value of it)
  2840. even if a deadline has a different individual lead time specified.
  2841. Custom commands can set this variable in the options section."
  2842. :group 'org-time
  2843. :group 'org-agenda-daily/weekly
  2844. :type 'integer)
  2845. (defcustom org-scheduled-delay-days 0
  2846. "Number of days before a scheduled item becomes active.
  2847. This variable governs the display in sparse trees and in the agenda.
  2848. The default value (i.e. 0) means: don't delay scheduled item.
  2849. When negative, it means use this number (the absolute value of it)
  2850. even if a scheduled item has a different individual delay time
  2851. specified.
  2852. Custom commands can set this variable in the options section."
  2853. :group 'org-time
  2854. :group 'org-agenda-daily/weekly
  2855. :version "24.4"
  2856. :package-version '(Org . "8.0")
  2857. :type 'integer)
  2858. (defcustom org-read-date-prefer-future t
  2859. "Non-nil means assume future for incomplete date input from user.
  2860. This affects the following situations:
  2861. 1. The user gives a month but not a year.
  2862. For example, if it is April and you enter \"feb 2\", this will be read
  2863. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2864. 2. The user gives a day, but no month.
  2865. For example, if today is the 15th, and you enter \"3\", Org-mode will
  2866. read this as the third of *next* month. However, if you enter \"17\",
  2867. it will be considered as *this* month.
  2868. If you set this variable to the symbol `time', then also the following
  2869. will work:
  2870. 3. If the user gives a time.
  2871. If the time is before now, it will be interpreted as tomorrow.
  2872. Currently none of this works for ISO week specifications.
  2873. When this option is nil, the current day, month and year will always be
  2874. used as defaults.
  2875. See also `org-agenda-jump-prefer-future'."
  2876. :group 'org-time
  2877. :type '(choice
  2878. (const :tag "Never" nil)
  2879. (const :tag "Check month and day" t)
  2880. (const :tag "Check month, day, and time" time)))
  2881. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2882. "Should the agenda jump command prefer the future for incomplete dates?
  2883. The default is to do the same as configured in `org-read-date-prefer-future'.
  2884. But you can also set a deviating value here.
  2885. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2886. :group 'org-agenda
  2887. :group 'org-time
  2888. :version "24.1"
  2889. :type '(choice
  2890. (const :tag "Use org-read-date-prefer-future"
  2891. org-read-date-prefer-future)
  2892. (const :tag "Never" nil)
  2893. (const :tag "Always" t)))
  2894. (defcustom org-read-date-force-compatible-dates t
  2895. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2896. Depending on the system Emacs is running on, certain dates cannot
  2897. be represented with the type used internally to represent time.
  2898. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2899. correctly. Some systems allow for earlier dates, some for later,
  2900. some for both. One way to find out it to insert any date into an
  2901. Org buffer, putting the cursor on the year and hitting S-up and
  2902. S-down to test the range.
  2903. When this variable is set to t, the date/time prompt will not let
  2904. you specify dates outside the 1970-2037 range, so it is certain that
  2905. these dates will work in whatever version of Emacs you are
  2906. running, and also that you can move a file from one Emacs implementation
  2907. to another. WHenever Org is forcing the year for you, it will display
  2908. a message and beep.
  2909. When this variable is nil, Org will check if the date is
  2910. representable in the specific Emacs implementation you are using.
  2911. If not, it will force a year, usually the current year, and beep
  2912. to remind you. Currently this setting is not recommended because
  2913. the likelihood that you will open your Org files in an Emacs that
  2914. has limited date range is not negligible.
  2915. A workaround for this problem is to use diary sexp dates for time
  2916. stamps outside of this range."
  2917. :group 'org-time
  2918. :version "24.1"
  2919. :type 'boolean)
  2920. (defcustom org-read-date-display-live t
  2921. "Non-nil means display current interpretation of date prompt live.
  2922. This display will be in an overlay, in the minibuffer."
  2923. :group 'org-time
  2924. :type 'boolean)
  2925. (defcustom org-read-date-popup-calendar t
  2926. "Non-nil means pop up a calendar when prompting for a date.
  2927. In the calendar, the date can be selected with mouse-1. However, the
  2928. minibuffer will also be active, and you can simply enter the date as well.
  2929. When nil, only the minibuffer will be available."
  2930. :group 'org-time
  2931. :type 'boolean)
  2932. (org-defvaralias 'org-popup-calendar-for-date-prompt
  2933. 'org-read-date-popup-calendar)
  2934. (make-obsolete-variable
  2935. 'org-read-date-minibuffer-setup-hook
  2936. "Set `org-read-date-minibuffer-local-map' instead." "24.4")
  2937. (defcustom org-read-date-minibuffer-setup-hook nil
  2938. "Hook to be used to set up keys for the date/time interface.
  2939. Add key definitions to `minibuffer-local-map', which will be a
  2940. temporary copy.
  2941. WARNING: This option is obsolete, you should use
  2942. `org-read-date-minibuffer-local-map' to set up keys."
  2943. :group 'org-time
  2944. :type 'hook)
  2945. (defcustom org-extend-today-until 0
  2946. "The hour when your day really ends. Must be an integer.
  2947. This has influence for the following applications:
  2948. - When switching the agenda to \"today\". It it is still earlier than
  2949. the time given here, the day recognized as TODAY is actually yesterday.
  2950. - When a date is read from the user and it is still before the time given
  2951. here, the current date and time will be assumed to be yesterday, 23:59.
  2952. Also, timestamps inserted in capture templates follow this rule.
  2953. IMPORTANT: This is a feature whose implementation is and likely will
  2954. remain incomplete. Really, it is only here because past midnight seems to
  2955. be the favorite working time of John Wiegley :-)"
  2956. :group 'org-time
  2957. :type 'integer)
  2958. (defcustom org-use-effective-time nil
  2959. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2960. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2961. \"effective time\" of any timestamps between midnight and 8am will be
  2962. 23:59 of the previous day."
  2963. :group 'org-time
  2964. :version "24.1"
  2965. :type 'boolean)
  2966. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2967. "When non-nil, use the last clock out time for `org-todo'.
  2968. Note that this option has precedence over the combined use of
  2969. `org-use-effective-time' and `org-extend-today-until'."
  2970. :group 'org-time
  2971. :version "24.4"
  2972. :package-version '(Org . "8.0")
  2973. :type 'boolean)
  2974. (defcustom org-edit-timestamp-down-means-later nil
  2975. "Non-nil means S-down will increase the time in a time stamp.
  2976. When nil, S-up will increase."
  2977. :group 'org-time
  2978. :type 'boolean)
  2979. (defcustom org-calendar-follow-timestamp-change t
  2980. "Non-nil means make the calendar window follow timestamp changes.
  2981. When a timestamp is modified and the calendar window is visible, it will be
  2982. moved to the new date."
  2983. :group 'org-time
  2984. :type 'boolean)
  2985. (defgroup org-tags nil
  2986. "Options concerning tags in Org-mode."
  2987. :tag "Org Tags"
  2988. :group 'org)
  2989. (defcustom org-tag-alist nil
  2990. "List of tags allowed in Org-mode files.
  2991. When this list is nil, Org-mode will base TAG input on what is already in the
  2992. buffer.
  2993. The value of this variable is an alist, the car of each entry must be a
  2994. keyword as a string, the cdr may be a character that is used to select
  2995. that tag through the fast-tag-selection interface.
  2996. See the manual for details."
  2997. :group 'org-tags
  2998. :type '(repeat
  2999. (choice
  3000. (cons (string :tag "Tag name")
  3001. (character :tag "Access char"))
  3002. (list :tag "Start radio group"
  3003. (const :startgroup)
  3004. (option (string :tag "Group description")))
  3005. (list :tag "Start tag group, non distinct"
  3006. (const :startgrouptag)
  3007. (option (string :tag "Group description")))
  3008. (list :tag "Group tags delimiter"
  3009. (const :grouptags))
  3010. (list :tag "End radio group"
  3011. (const :endgroup)
  3012. (option (string :tag "Group description")))
  3013. (list :tag "End tag group, non distinct"
  3014. (const :endgrouptag)
  3015. (option (string :tag "Group description")))
  3016. (const :tag "New line" (:newline)))))
  3017. (defcustom org-tag-persistent-alist nil
  3018. "List of tags that will always appear in all Org-mode files.
  3019. This is in addition to any in buffer settings or customizations
  3020. of `org-tag-alist'.
  3021. When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
  3022. The value of this variable is an alist, the car of each entry must be a
  3023. keyword as a string, the cdr may be a character that is used to select
  3024. that tag through the fast-tag-selection interface.
  3025. See the manual for details.
  3026. To disable these tags on a per-file basis, insert anywhere in the file:
  3027. #+STARTUP: noptag"
  3028. :group 'org-tags
  3029. :type '(repeat
  3030. (choice
  3031. (cons (string :tag "Tag name")
  3032. (character :tag "Access char"))
  3033. (const :tag "Start radio group" (:startgroup))
  3034. (const :tag "Group tags delimiter" (:grouptags))
  3035. (const :tag "End radio group" (:endgroup))
  3036. (const :tag "New line" (:newline)))))
  3037. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3038. "If non-nil, always offer completion for all tags of all agenda files.
  3039. Instead of customizing this variable directly, you might want to
  3040. set it locally for capture buffers, because there no list of
  3041. tags in that file can be created dynamically (there are none).
  3042. (add-hook \\='org-capture-mode-hook
  3043. (lambda ()
  3044. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3045. :group 'org-tags
  3046. :version "24.1"
  3047. :type 'boolean)
  3048. (defvar org-file-tags nil
  3049. "List of tags that can be inherited by all entries in the file.
  3050. The tags will be inherited if the variable `org-use-tag-inheritance'
  3051. says they should be.
  3052. This variable is populated from #+FILETAGS lines.")
  3053. (defcustom org-use-fast-tag-selection 'auto
  3054. "Non-nil means use fast tag selection scheme.
  3055. This is a special interface to select and deselect tags with single keys.
  3056. When nil, fast selection is never used.
  3057. When the symbol `auto', fast selection is used if and only if selection
  3058. characters for tags have been configured, either through the variable
  3059. `org-tag-alist' or through a #+TAGS line in the buffer.
  3060. When t, fast selection is always used and selection keys are assigned
  3061. automatically if necessary."
  3062. :group 'org-tags
  3063. :type '(choice
  3064. (const :tag "Always" t)
  3065. (const :tag "Never" nil)
  3066. (const :tag "When selection characters are configured" auto)))
  3067. (defcustom org-fast-tag-selection-single-key nil
  3068. "Non-nil means fast tag selection exits after first change.
  3069. When nil, you have to press RET to exit it.
  3070. During fast tag selection, you can toggle this flag with `C-c'.
  3071. This variable can also have the value `expert'. In this case, the window
  3072. displaying the tags menu is not even shown, until you press C-c again."
  3073. :group 'org-tags
  3074. :type '(choice
  3075. (const :tag "No" nil)
  3076. (const :tag "Yes" t)
  3077. (const :tag "Expert" expert)))
  3078. (defvar org-fast-tag-selection-include-todo nil
  3079. "Non-nil means fast tags selection interface will also offer TODO states.
  3080. This is an undocumented feature, you should not rely on it.")
  3081. (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
  3082. "The column to which tags should be indented in a headline.
  3083. If this number is positive, it specifies the column. If it is negative,
  3084. it means that the tags should be flushright to that column. For example,
  3085. -80 works well for a normal 80 character screen.
  3086. When 0, place tags directly after headline text, with only one space in
  3087. between."
  3088. :group 'org-tags
  3089. :type 'integer)
  3090. (defcustom org-auto-align-tags t
  3091. "Non-nil keeps tags aligned when modifying headlines.
  3092. Some operations (i.e. demoting) change the length of a headline and
  3093. therefore shift the tags around. With this option turned on, after
  3094. each such operation the tags are again aligned to `org-tags-column'."
  3095. :group 'org-tags
  3096. :type 'boolean)
  3097. (defcustom org-use-tag-inheritance t
  3098. "Non-nil means tags in levels apply also for sublevels.
  3099. When nil, only the tags directly given in a specific line apply there.
  3100. This may also be a list of tags that should be inherited, or a regexp that
  3101. matches tags that should be inherited. Additional control is possible
  3102. with the variable `org-tags-exclude-from-inheritance' which gives an
  3103. explicit list of tags to be excluded from inheritance, even if the value of
  3104. `org-use-tag-inheritance' would select it for inheritance.
  3105. If this option is t, a match early-on in a tree can lead to a large
  3106. number of matches in the subtree when constructing the agenda or creating
  3107. a sparse tree. If you only want to see the first match in a tree during
  3108. a search, check out the variable `org-tags-match-list-sublevels'."
  3109. :group 'org-tags
  3110. :type '(choice
  3111. (const :tag "Not" nil)
  3112. (const :tag "Always" t)
  3113. (repeat :tag "Specific tags" (string :tag "Tag"))
  3114. (regexp :tag "Tags matched by regexp")))
  3115. (defcustom org-tags-exclude-from-inheritance nil
  3116. "List of tags that should never be inherited.
  3117. This is a way to exclude a few tags from inheritance. For way to do
  3118. the opposite, to actively allow inheritance for selected tags,
  3119. see the variable `org-use-tag-inheritance'."
  3120. :group 'org-tags
  3121. :type '(repeat (string :tag "Tag")))
  3122. (defun org-tag-inherit-p (tag)
  3123. "Check if TAG is one that should be inherited."
  3124. (cond
  3125. ((member tag org-tags-exclude-from-inheritance) nil)
  3126. ((eq org-use-tag-inheritance t) t)
  3127. ((not org-use-tag-inheritance) nil)
  3128. ((stringp org-use-tag-inheritance)
  3129. (string-match org-use-tag-inheritance tag))
  3130. ((listp org-use-tag-inheritance)
  3131. (member tag org-use-tag-inheritance))
  3132. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3133. (defcustom org-tags-match-list-sublevels t
  3134. "Non-nil means list also sublevels of headlines matching a search.
  3135. This variable applies to tags/property searches, and also to stuck
  3136. projects because this search is based on a tags match as well.
  3137. When set to the symbol `indented', sublevels are indented with
  3138. leading dots.
  3139. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3140. the sublevels of a headline matching a tag search often also match
  3141. the same search. Listing all of them can create very long lists.
  3142. Setting this variable to nil causes subtrees of a match to be skipped.
  3143. This variable is semi-obsolete and probably should always be true. It
  3144. is better to limit inheritance to certain tags using the variables
  3145. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3146. :group 'org-tags
  3147. :type '(choice
  3148. (const :tag "No, don't list them" nil)
  3149. (const :tag "Yes, do list them" t)
  3150. (const :tag "List them, indented with leading dots" indented)))
  3151. (defcustom org-tags-sort-function nil
  3152. "When set, tags are sorted using this function as a comparator."
  3153. :group 'org-tags
  3154. :type '(choice
  3155. (const :tag "No sorting" nil)
  3156. (const :tag "Alphabetical" string<)
  3157. (const :tag "Reverse alphabetical" string>)
  3158. (function :tag "Custom function" nil)))
  3159. (defvar org-tags-history nil
  3160. "History of minibuffer reads for tags.")
  3161. (defvar org-last-tags-completion-table nil
  3162. "The last used completion table for tags.")
  3163. (defvar org-after-tags-change-hook nil
  3164. "Hook that is run after the tags in a line have changed.")
  3165. (defgroup org-properties nil
  3166. "Options concerning properties in Org-mode."
  3167. :tag "Org Properties"
  3168. :group 'org)
  3169. (defcustom org-property-format "%-10s %s"
  3170. "How property key/value pairs should be formatted by `indent-line'.
  3171. When `indent-line' hits a property definition, it will format the line
  3172. according to this format, mainly to make sure that the values are
  3173. lined-up with respect to each other."
  3174. :group 'org-properties
  3175. :type 'string)
  3176. (defcustom org-properties-postprocess-alist nil
  3177. "Alist of properties and functions to adjust inserted values.
  3178. Elements of this alist must be of the form
  3179. ([string] [function])
  3180. where [string] must be a property name and [function] must be a
  3181. lambda expression: this lambda expression must take one argument,
  3182. the value to adjust, and return the new value as a string.
  3183. For example, this element will allow the property \"Remaining\"
  3184. to be updated wrt the relation between the \"Effort\" property
  3185. and the clock summary:
  3186. ((\"Remaining\" (lambda(value)
  3187. (let ((clocksum (org-clock-sum-current-item))
  3188. (effort (org-duration-string-to-minutes
  3189. (org-entry-get (point) \"Effort\"))))
  3190. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3191. :group 'org-properties
  3192. :version "24.1"
  3193. :type '(alist :key-type (string :tag "Property")
  3194. :value-type (function :tag "Function")))
  3195. (defcustom org-use-property-inheritance nil
  3196. "Non-nil means properties apply also for sublevels.
  3197. This setting is chiefly used during property searches. Turning it on can
  3198. cause significant overhead when doing a search, which is why it is not
  3199. on by default.
  3200. When nil, only the properties directly given in the current entry count.
  3201. When t, every property is inherited. The value may also be a list of
  3202. properties that should have inheritance, or a regular expression matching
  3203. properties that should be inherited.
  3204. However, note that some special properties use inheritance under special
  3205. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3206. and the properties ending in \"_ALL\" when they are used as descriptor
  3207. for valid values of a property.
  3208. Note for programmers:
  3209. When querying an entry with `org-entry-get', you can control if inheritance
  3210. should be used. By default, `org-entry-get' looks only at the local
  3211. properties. You can request inheritance by setting the inherit argument
  3212. to t (to force inheritance) or to `selective' (to respect the setting
  3213. in this variable)."
  3214. :group 'org-properties
  3215. :type '(choice
  3216. (const :tag "Not" nil)
  3217. (const :tag "Always" t)
  3218. (repeat :tag "Specific properties" (string :tag "Property"))
  3219. (regexp :tag "Properties matched by regexp")))
  3220. (defun org-property-inherit-p (property)
  3221. "Check if PROPERTY is one that should be inherited."
  3222. (cond
  3223. ((eq org-use-property-inheritance t) t)
  3224. ((not org-use-property-inheritance) nil)
  3225. ((stringp org-use-property-inheritance)
  3226. (string-match org-use-property-inheritance property))
  3227. ((listp org-use-property-inheritance)
  3228. (member property org-use-property-inheritance))
  3229. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3230. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3231. "The default column format, if no other format has been defined.
  3232. This variable can be set on the per-file basis by inserting a line
  3233. #+COLUMNS: %25ITEM ....."
  3234. :group 'org-properties
  3235. :type 'string)
  3236. (defcustom org-columns-ellipses ".."
  3237. "The ellipses to be used when a field in column view is truncated.
  3238. When this is the empty string, as many characters as possible are shown,
  3239. but then there will be no visual indication that the field has been truncated.
  3240. When this is a string of length N, the last N characters of a truncated
  3241. field are replaced by this string. If the column is narrower than the
  3242. ellipses string, only part of the ellipses string will be shown."
  3243. :group 'org-properties
  3244. :type 'string)
  3245. (defcustom org-columns-modify-value-for-display-function nil
  3246. "Function that modifies values for display in column view.
  3247. For example, it can be used to cut out a certain part from a time stamp.
  3248. The function must take 2 arguments:
  3249. column-title The title of the column (*not* the property name)
  3250. value The value that should be modified.
  3251. The function should return the value that should be displayed,
  3252. or nil if the normal value should be used."
  3253. :group 'org-properties
  3254. :type '(choice (const nil) (function)))
  3255. (defconst org-global-properties-fixed
  3256. '(("VISIBILITY_ALL" . "folded children content all")
  3257. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3258. "List of property/value pairs that can be inherited by any entry.
  3259. These are fixed values, for the preset properties. The user variable
  3260. that can be used to add to this list is `org-global-properties'.
  3261. The entries in this list are cons cells where the car is a property
  3262. name and cdr is a string with the value. If the value represents
  3263. multiple items like an \"_ALL\" property, separate the items by
  3264. spaces.")
  3265. (defcustom org-global-properties nil
  3266. "List of property/value pairs that can be inherited by any entry.
  3267. This list will be combined with the constant `org-global-properties-fixed'.
  3268. The entries in this list are cons cells where the car is a property
  3269. name and cdr is a string with the value.
  3270. You can set buffer-local values for the same purpose in the variable
  3271. `org-file-properties' this by adding lines like
  3272. #+PROPERTY: NAME VALUE"
  3273. :group 'org-properties
  3274. :type '(repeat
  3275. (cons (string :tag "Property")
  3276. (string :tag "Value"))))
  3277. (defvar-local org-file-properties nil
  3278. "List of property/value pairs that can be inherited by any entry.
  3279. Valid for the current buffer.
  3280. This variable is populated from #+PROPERTY lines.")
  3281. (defgroup org-agenda nil
  3282. "Options concerning agenda views in Org-mode."
  3283. :tag "Org Agenda"
  3284. :group 'org)
  3285. (defvar-local org-category nil
  3286. "Variable used by org files to set a category for agenda display.
  3287. Such files should use a file variable to set it, for example
  3288. # -*- mode: org; org-category: \"ELisp\"
  3289. or contain a special line
  3290. #+CATEGORY: ELisp
  3291. If the file does not specify a category, then file's base name
  3292. is used instead.")
  3293. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3294. (defcustom org-agenda-files nil
  3295. "The files to be used for agenda display.
  3296. Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
  3297. \\[org-remove-file]. You can also use customize to edit the list.
  3298. If an entry is a directory, all files in that directory that are matched by
  3299. `org-agenda-file-regexp' will be part of the file list.
  3300. If the value of the variable is not a list but a single file name, then
  3301. the list of agenda files is actually stored and maintained in that file, one
  3302. agenda file per line. In this file paths can be given relative to
  3303. `org-directory'. Tilde expansion and environment variable substitution
  3304. are also made."
  3305. :group 'org-agenda
  3306. :type '(choice
  3307. (repeat :tag "List of files and directories" file)
  3308. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3309. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3310. "Regular expression to match files for `org-agenda-files'.
  3311. If any element in the list in that variable contains a directory instead
  3312. of a normal file, all files in that directory that are matched by this
  3313. regular expression will be included."
  3314. :group 'org-agenda
  3315. :type 'regexp)
  3316. (defcustom org-agenda-text-search-extra-files nil
  3317. "List of extra files to be searched by text search commands.
  3318. These files will be searched in addition to the agenda files by the
  3319. commands `org-search-view' (`\\[org-agenda] s') \
  3320. and `org-occur-in-agenda-files'.
  3321. Note that these files will only be searched for text search commands,
  3322. not for the other agenda views like todo lists, tag searches or the weekly
  3323. agenda. This variable is intended to list notes and possibly archive files
  3324. that should also be searched by these two commands.
  3325. In fact, if the first element in the list is the symbol `agenda-archives',
  3326. then all archive files of all agenda files will be added to the search
  3327. scope."
  3328. :group 'org-agenda
  3329. :type '(set :greedy t
  3330. (const :tag "Agenda Archives" agenda-archives)
  3331. (repeat :inline t (file))))
  3332. (org-defvaralias 'org-agenda-multi-occur-extra-files
  3333. 'org-agenda-text-search-extra-files)
  3334. (defcustom org-agenda-skip-unavailable-files nil
  3335. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3336. A nil value means to remove them, after a query, from the list."
  3337. :group 'org-agenda
  3338. :type 'boolean)
  3339. (defcustom org-calendar-to-agenda-key [?c]
  3340. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3341. The command `org-calendar-goto-agenda' will be bound to this key. The
  3342. default is the character `c' because then `c' can be used to switch back and
  3343. forth between agenda and calendar."
  3344. :group 'org-agenda
  3345. :type 'sexp)
  3346. (defcustom org-calendar-insert-diary-entry-key [?i]
  3347. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3348. This option is irrelevant until `org-agenda-diary-file' has been configured
  3349. to point to an Org-mode file. When that is the case, the command
  3350. `org-agenda-diary-entry' will be bound to the key given here, by default
  3351. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3352. if you want to continue doing this, you need to change this to a different
  3353. key."
  3354. :group 'org-agenda
  3355. :type 'sexp)
  3356. (defcustom org-agenda-diary-file 'diary-file
  3357. "File to which to add new entries with the `i' key in agenda and calendar.
  3358. When this is the symbol `diary-file', the functionality in the Emacs
  3359. calendar will be used to add entries to the `diary-file'. But when this
  3360. points to a file, `org-agenda-diary-entry' will be used instead."
  3361. :group 'org-agenda
  3362. :type '(choice
  3363. (const :tag "The standard Emacs diary file" diary-file)
  3364. (file :tag "Special Org file diary entries")))
  3365. (eval-after-load "calendar"
  3366. '(progn
  3367. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3368. 'org-calendar-goto-agenda)
  3369. (add-hook 'calendar-mode-hook
  3370. (lambda ()
  3371. (unless (eq org-agenda-diary-file 'diary-file)
  3372. (define-key calendar-mode-map
  3373. org-calendar-insert-diary-entry-key
  3374. 'org-agenda-diary-entry))))))
  3375. (defgroup org-latex nil
  3376. "Options for embedding LaTeX code into Org-mode."
  3377. :tag "Org LaTeX"
  3378. :group 'org)
  3379. (defcustom org-format-latex-options
  3380. '(:foreground default :background default :scale 1.0
  3381. :html-foreground "Black" :html-background "Transparent"
  3382. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3383. "Options for creating images from LaTeX fragments.
  3384. This is a property list with the following properties:
  3385. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3386. `default' means use the foreground of the default face.
  3387. `auto' means use the foreground from the text face.
  3388. :background the background color, or \"Transparent\".
  3389. `default' means use the background of the default face.
  3390. `auto' means use the background from the text face.
  3391. :scale a scaling factor for the size of the images, to get more pixels
  3392. :html-foreground, :html-background, :html-scale
  3393. the same numbers for HTML export.
  3394. :matchers a list indicating which matchers should be used to
  3395. find LaTeX fragments. Valid members of this list are:
  3396. \"begin\" find environments
  3397. \"$1\" find single characters surrounded by $.$
  3398. \"$\" find math expressions surrounded by $...$
  3399. \"$$\" find math expressions surrounded by $$....$$
  3400. \"\\(\" find math expressions surrounded by \\(...\\)
  3401. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3402. :group 'org-latex
  3403. :type 'plist)
  3404. (defcustom org-format-latex-signal-error t
  3405. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3406. When nil, just push out a message."
  3407. :group 'org-latex
  3408. :version "24.1"
  3409. :type 'boolean)
  3410. (defcustom org-latex-to-mathml-jar-file nil
  3411. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3412. Use this to specify additional executable file say a jar file.
  3413. When using MathToWeb as the converter, specify the full-path to
  3414. your mathtoweb.jar file."
  3415. :group 'org-latex
  3416. :version "24.1"
  3417. :type '(choice
  3418. (const :tag "None" nil)
  3419. (file :tag "JAR file" :must-match t)))
  3420. (defcustom org-latex-to-mathml-convert-command nil
  3421. "Command to convert LaTeX fragments to MathML.
  3422. Replace format-specifiers in the command as noted below and use
  3423. `shell-command' to convert LaTeX to MathML.
  3424. %j: Executable file in fully expanded form as specified by
  3425. `org-latex-to-mathml-jar-file'.
  3426. %I: Input LaTeX file in fully expanded form.
  3427. %i: The latex fragment to be converted.
  3428. %o: Output MathML file.
  3429. This command is used by `org-create-math-formula'.
  3430. When using MathToWeb as the converter, set this option to
  3431. \"java -jar %j -unicode -force -df %o %I\".
  3432. When using LaTeXML set this option to
  3433. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3434. :group 'org-latex
  3435. :version "24.1"
  3436. :type '(choice
  3437. (const :tag "None" nil)
  3438. (string :tag "\nShell command")))
  3439. (defcustom org-latex-create-formula-image-program 'dvipng
  3440. "Program to convert LaTeX fragments with.
  3441. dvipng Process the LaTeX fragments to dvi file, then convert
  3442. dvi files to png files using dvipng.
  3443. This will also include processing of non-math environments.
  3444. imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
  3445. to convert pdf files to png files"
  3446. :group 'org-latex
  3447. :version "24.1"
  3448. :type '(choice
  3449. (const :tag "dvipng" dvipng)
  3450. (const :tag "imagemagick" imagemagick)))
  3451. (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
  3452. "Path to store latex preview images.
  3453. A relative path here creates many directories relative to the
  3454. processed org files paths. An absolute path puts all preview
  3455. images at the same place."
  3456. :group 'org-latex
  3457. :version "24.3"
  3458. :type 'string)
  3459. (defun org-format-latex-mathml-available-p ()
  3460. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3461. (save-match-data
  3462. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3463. org-latex-to-mathml-convert-command)
  3464. (let ((executable (car (split-string
  3465. org-latex-to-mathml-convert-command))))
  3466. (when (executable-find executable)
  3467. (if (string-match
  3468. "%j" org-latex-to-mathml-convert-command)
  3469. (file-readable-p org-latex-to-mathml-jar-file)
  3470. t))))))
  3471. (defcustom org-format-latex-header "\\documentclass{article}
  3472. \\usepackage[usenames]{color}
  3473. \[PACKAGES]
  3474. \[DEFAULT-PACKAGES]
  3475. \\pagestyle{empty} % do not remove
  3476. % The settings below are copied from fullpage.sty
  3477. \\setlength{\\textwidth}{\\paperwidth}
  3478. \\addtolength{\\textwidth}{-3cm}
  3479. \\setlength{\\oddsidemargin}{1.5cm}
  3480. \\addtolength{\\oddsidemargin}{-2.54cm}
  3481. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3482. \\setlength{\\textheight}{\\paperheight}
  3483. \\addtolength{\\textheight}{-\\headheight}
  3484. \\addtolength{\\textheight}{-\\headsep}
  3485. \\addtolength{\\textheight}{-\\footskip}
  3486. \\addtolength{\\textheight}{-3cm}
  3487. \\setlength{\\topmargin}{1.5cm}
  3488. \\addtolength{\\topmargin}{-2.54cm}"
  3489. "The document header used for processing LaTeX fragments.
  3490. It is imperative that this header make sure that no page number
  3491. appears on the page. The package defined in the variables
  3492. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3493. will either replace the placeholder \"[PACKAGES]\" in this
  3494. header, or they will be appended."
  3495. :group 'org-latex
  3496. :type 'string)
  3497. (defun org-set-packages-alist (var val)
  3498. "Set the packages alist and make sure it has 3 elements per entry."
  3499. (set var (mapcar (lambda (x)
  3500. (if (and (consp x) (= (length x) 2))
  3501. (list (car x) (nth 1 x) t)
  3502. x))
  3503. val)))
  3504. (defun org-get-packages-alist (var)
  3505. "Get the packages alist and make sure it has 3 elements per entry."
  3506. (mapcar (lambda (x)
  3507. (if (and (consp x) (= (length x) 2))
  3508. (list (car x) (nth 1 x) t)
  3509. x))
  3510. (default-value var)))
  3511. (defcustom org-latex-default-packages-alist
  3512. '(("AUTO" "inputenc" t ("pdflatex"))
  3513. ("T1" "fontenc" t ("pdflatex"))
  3514. ("" "graphicx" t)
  3515. ("" "grffile" t)
  3516. ("" "longtable" nil)
  3517. ("" "wrapfig" nil)
  3518. ("" "rotating" nil)
  3519. ("normalem" "ulem" t)
  3520. ("" "amsmath" t)
  3521. ("" "textcomp" t)
  3522. ("" "amssymb" t)
  3523. ("" "capt-of" nil)
  3524. ("" "hyperref" nil))
  3525. "Alist of default packages to be inserted in the header.
  3526. Change this only if one of the packages here causes an
  3527. incompatibility with another package you are using.
  3528. The packages in this list are needed by one part or another of
  3529. Org mode to function properly:
  3530. - inputenc, fontenc: for basic font and character selection
  3531. - graphicx: for including images
  3532. - grffile: allow periods and spaces in graphics file names
  3533. - longtable: For multipage tables
  3534. - wrapfig: for figure placement
  3535. - rotating: for sideways figures and tables
  3536. - ulem: for underline and strike-through
  3537. - amsmath: for subscript and superscript and math environments
  3538. - textcomp, amssymb: for various symbols used
  3539. for interpreting the entities in `org-entities'. You can skip
  3540. some of these packages if you don't use any of their symbols.
  3541. - capt-of: for captions outside of floats
  3542. - hyperref: for cross references
  3543. Therefore you should not modify this variable unless you know
  3544. what you are doing. The one reason to change it anyway is that
  3545. you might be loading some other package that conflicts with one
  3546. of the default packages. Each element is either a cell or
  3547. a string.
  3548. A cell is of the format
  3549. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3550. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3551. when compiling LaTeX snippets into images for inclusion into
  3552. non-LaTeX output. COMPILERS is a list of compilers that should
  3553. include the package, see `org-latex-compiler'. If the document
  3554. compiler is not in the list, and the list is non-nil, the package
  3555. will not be inserted in the final document.
  3556. A string will be inserted as-is in the header of the document."
  3557. :group 'org-latex
  3558. :group 'org-export-latex
  3559. :set 'org-set-packages-alist
  3560. :get 'org-get-packages-alist
  3561. :version "25.1"
  3562. :package-version '(Org . "8.3")
  3563. :type '(repeat
  3564. (choice
  3565. (list :tag "options/package pair"
  3566. (string :tag "options")
  3567. (string :tag "package")
  3568. (boolean :tag "Snippet"))
  3569. (string :tag "A line of LaTeX"))))
  3570. (defcustom org-latex-packages-alist nil
  3571. "Alist of packages to be inserted in every LaTeX header.
  3572. These will be inserted after `org-latex-default-packages-alist'.
  3573. Each element is either a cell or a string.
  3574. A cell is of the format:
  3575. (\"options\" \"package\" SNIPPET-FLAG)
  3576. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3577. needed when turning LaTeX snippets into images for inclusion into
  3578. non-LaTeX output.
  3579. A string will be inserted as-is in the header of the document.
  3580. Make sure that you only list packages here which:
  3581. - you want in every file;
  3582. - do not conflict with the setup in `org-format-latex-header';
  3583. - do not conflict with the default packages in
  3584. `org-latex-default-packages-alist'."
  3585. :group 'org-latex
  3586. :group 'org-export-latex
  3587. :set 'org-set-packages-alist
  3588. :get 'org-get-packages-alist
  3589. :type '(repeat
  3590. (choice
  3591. (list :tag "options/package pair"
  3592. (string :tag "options")
  3593. (string :tag "package")
  3594. (boolean :tag "Snippet"))
  3595. (string :tag "A line of LaTeX"))))
  3596. (defgroup org-appearance nil
  3597. "Settings for Org-mode appearance."
  3598. :tag "Org Appearance"
  3599. :group 'org)
  3600. (defcustom org-level-color-stars-only nil
  3601. "Non-nil means fontify only the stars in each headline.
  3602. When nil, the entire headline is fontified.
  3603. Changing it requires restart of `font-lock-mode' to become effective
  3604. also in regions already fontified."
  3605. :group 'org-appearance
  3606. :type 'boolean)
  3607. (defcustom org-hide-leading-stars nil
  3608. "Non-nil means hide the first N-1 stars in a headline.
  3609. This works by using the face `org-hide' for these stars. This
  3610. face is white for a light background, and black for a dark
  3611. background. You may have to customize the face `org-hide' to
  3612. make this work.
  3613. Changing it requires restart of `font-lock-mode' to become effective
  3614. also in regions already fontified.
  3615. You may also set this on a per-file basis by adding one of the following
  3616. lines to the buffer:
  3617. #+STARTUP: hidestars
  3618. #+STARTUP: showstars"
  3619. :group 'org-appearance
  3620. :type 'boolean)
  3621. (defcustom org-hidden-keywords nil
  3622. "List of symbols corresponding to keywords to be hidden the org buffer.
  3623. For example, a value \\='(title) for this list will make the document's title
  3624. appear in the buffer without the initial #+TITLE: keyword."
  3625. :group 'org-appearance
  3626. :version "24.1"
  3627. :type '(set (const :tag "#+AUTHOR" author)
  3628. (const :tag "#+DATE" date)
  3629. (const :tag "#+EMAIL" email)
  3630. (const :tag "#+TITLE" title)))
  3631. (defcustom org-custom-properties nil
  3632. "List of properties (as strings) with a special meaning.
  3633. The default use of these custom properties is to let the user
  3634. hide them with `org-toggle-custom-properties-visibility'."
  3635. :group 'org-properties
  3636. :group 'org-appearance
  3637. :version "24.3"
  3638. :type '(repeat (string :tag "Property Name")))
  3639. (defcustom org-fontify-done-headline nil
  3640. "Non-nil means change the face of a headline if it is marked DONE.
  3641. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3642. When this is non-nil, the headline after the keyword is set to the
  3643. `org-headline-done' as an additional indication."
  3644. :group 'org-appearance
  3645. :type 'boolean)
  3646. (defcustom org-fontify-emphasized-text t
  3647. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3648. Changing this variable requires a restart of Emacs to take effect."
  3649. :group 'org-appearance
  3650. :type 'boolean)
  3651. (defcustom org-fontify-whole-heading-line nil
  3652. "Non-nil means fontify the whole line for headings.
  3653. This is useful when setting a background color for the
  3654. org-level-* faces."
  3655. :group 'org-appearance
  3656. :type 'boolean)
  3657. (defcustom org-highlight-latex-and-related nil
  3658. "Non-nil means highlight LaTeX related syntax in the buffer.
  3659. When non nil, the value should be a list containing any of the
  3660. following symbols:
  3661. `latex' Highlight LaTeX snippets and environments.
  3662. `script' Highlight subscript and superscript.
  3663. `entities' Highlight entities."
  3664. :group 'org-appearance
  3665. :version "24.4"
  3666. :package-version '(Org . "8.0")
  3667. :type '(choice
  3668. (const :tag "No highlighting" nil)
  3669. (set :greedy t :tag "Highlight"
  3670. (const :tag "LaTeX snippets and environments" latex)
  3671. (const :tag "Subscript and superscript" script)
  3672. (const :tag "Entities" entities))))
  3673. (defcustom org-hide-emphasis-markers nil
  3674. "Non-nil mean font-lock should hide the emphasis marker characters."
  3675. :group 'org-appearance
  3676. :type 'boolean)
  3677. (defcustom org-hide-macro-markers nil
  3678. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3679. :group 'org-appearance
  3680. :type 'boolean)
  3681. (defcustom org-pretty-entities nil
  3682. "Non-nil means show entities as UTF8 characters.
  3683. When nil, the \\name form remains in the buffer."
  3684. :group 'org-appearance
  3685. :version "24.1"
  3686. :type 'boolean)
  3687. (defcustom org-pretty-entities-include-sub-superscripts t
  3688. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3689. :group 'org-appearance
  3690. :version "24.1"
  3691. :type 'boolean)
  3692. (defvar org-emph-re nil
  3693. "Regular expression for matching emphasis.
  3694. After a match, the match groups contain these elements:
  3695. 0 The match of the full regular expression, including the characters
  3696. before and after the proper match
  3697. 1 The character before the proper match, or empty at beginning of line
  3698. 2 The proper match, including the leading and trailing markers
  3699. 3 The leading marker like * or /, indicating the type of highlighting
  3700. 4 The text between the emphasis markers, not including the markers
  3701. 5 The character after the match, empty at the end of a line")
  3702. (defvar org-verbatim-re nil
  3703. "Regular expression for matching verbatim text.")
  3704. (defvar org-emphasis-regexp-components) ; defined just below
  3705. (defvar org-emphasis-alist) ; defined just below
  3706. (defun org-set-emph-re (var val)
  3707. "Set variable and compute the emphasis regular expression."
  3708. (set var val)
  3709. (when (and (boundp 'org-emphasis-alist)
  3710. (boundp 'org-emphasis-regexp-components)
  3711. org-emphasis-alist org-emphasis-regexp-components)
  3712. (let* ((e org-emphasis-regexp-components)
  3713. (pre (car e))
  3714. (post (nth 1 e))
  3715. (border (nth 2 e))
  3716. (body (nth 3 e))
  3717. (nl (nth 4 e))
  3718. (body1 (concat body "*?"))
  3719. (markers (mapconcat 'car org-emphasis-alist ""))
  3720. (vmarkers (mapconcat
  3721. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3722. org-emphasis-alist "")))
  3723. ;; make sure special characters appear at the right position in the class
  3724. (if (string-match "\\^" markers)
  3725. (setq markers (concat (replace-match "" t t markers) "^")))
  3726. (if (string-match "-" markers)
  3727. (setq markers (concat (replace-match "" t t markers) "-")))
  3728. (if (string-match "\\^" vmarkers)
  3729. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3730. (if (string-match "-" vmarkers)
  3731. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3732. (if (> nl 0)
  3733. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3734. (int-to-string nl) "\\}")))
  3735. ;; Make the regexp
  3736. (setq org-emph-re
  3737. (concat "\\([" pre "]\\|^\\)"
  3738. "\\("
  3739. "\\([" markers "]\\)"
  3740. "\\("
  3741. "[^" border "]\\|"
  3742. "[^" border "]"
  3743. body1
  3744. "[^" border "]"
  3745. "\\)"
  3746. "\\3\\)"
  3747. "\\([" post "]\\|$\\)"))
  3748. (setq org-verbatim-re
  3749. (concat "\\([" pre "]\\|^\\)"
  3750. "\\("
  3751. "\\([" vmarkers "]\\)"
  3752. "\\("
  3753. "[^" border "]\\|"
  3754. "[^" border "]"
  3755. body1
  3756. "[^" border "]"
  3757. "\\)"
  3758. "\\3\\)"
  3759. "\\([" post "]\\|$\\)")))))
  3760. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3761. ;; set this option proved cumbersome. See this message/thread:
  3762. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3763. (defvar org-emphasis-regexp-components
  3764. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3765. "Components used to build the regular expression for emphasis.
  3766. This is a list with five entries. Terminology: In an emphasis string
  3767. like \" *strong word* \", we call the initial space PREMATCH, the final
  3768. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3769. and \"trong wor\" is the body. The different components in this variable
  3770. specify what is allowed/forbidden in each part:
  3771. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3772. post Chars allowed as postmatch. End of line will be allowed too.
  3773. border The chars *forbidden* as border characters.
  3774. body-regexp A regexp like \".\" to match a body character. Don't use
  3775. non-shy groups here, and don't allow newline here.
  3776. newline The maximum number of newlines allowed in an emphasis exp.
  3777. You need to reload Org or to restart Emacs after customizing this.")
  3778. (defcustom org-emphasis-alist
  3779. `(("*" bold)
  3780. ("/" italic)
  3781. ("_" underline)
  3782. ("=" org-verbatim verbatim)
  3783. ("~" org-code verbatim)
  3784. ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
  3785. "Alist of characters and faces to emphasize text.
  3786. Text starting and ending with a special character will be emphasized,
  3787. for example *bold*, _underlined_ and /italic/. This variable sets the
  3788. marker characters and the face to be used by font-lock for highlighting
  3789. in Org-mode Emacs buffers.
  3790. You need to reload Org or to restart Emacs after customizing this."
  3791. :group 'org-appearance
  3792. :set 'org-set-emph-re
  3793. :version "24.4"
  3794. :package-version '(Org . "8.0")
  3795. :type '(repeat
  3796. (list
  3797. (string :tag "Marker character")
  3798. (choice
  3799. (face :tag "Font-lock-face")
  3800. (plist :tag "Face property list"))
  3801. (option (const verbatim)))))
  3802. (defvar org-protecting-blocks
  3803. '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
  3804. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3805. This is needed for font-lock setup.")
  3806. ;;; Miscellaneous options
  3807. (defgroup org-completion nil
  3808. "Completion in Org-mode."
  3809. :tag "Org Completion"
  3810. :group 'org)
  3811. (defcustom org-completion-use-ido nil
  3812. "Non-nil means use ido completion wherever possible.
  3813. Note that `ido-mode' must be active for this variable to be relevant.
  3814. If you decide to turn this variable on, you might well want to turn off
  3815. `org-outline-path-complete-in-steps'.
  3816. See also `org-completion-use-iswitchb'."
  3817. :group 'org-completion
  3818. :type 'boolean)
  3819. (defcustom org-completion-use-iswitchb nil
  3820. "Non-nil means use iswitchb completion wherever possible.
  3821. Note that `iswitchb-mode' must be active for this variable to be relevant.
  3822. If you decide to turn this variable on, you might well want to turn off
  3823. `org-outline-path-complete-in-steps'.
  3824. Note that this variable has only an effect if `org-completion-use-ido' is nil."
  3825. :group 'org-completion
  3826. :type 'boolean)
  3827. (defcustom org-completion-fallback-command 'hippie-expand
  3828. "The expansion command called by \\[pcomplete] in normal context.
  3829. Normal means, no org-mode-specific context."
  3830. :group 'org-completion
  3831. :type 'function)
  3832. ;;; Functions and variables from their packages
  3833. ;; Declared here to avoid compiler warnings
  3834. ;; XEmacs only
  3835. (defvar outline-mode-menu-heading)
  3836. (defvar outline-mode-menu-show)
  3837. (defvar outline-mode-menu-hide)
  3838. (defvar zmacs-regions) ; XEmacs regions
  3839. ;; Emacs only
  3840. (defvar mark-active)
  3841. ;; Various packages
  3842. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3843. (declare-function calendar-forward-day "cal-move" (arg))
  3844. (declare-function calendar-goto-date "cal-move" (date))
  3845. (declare-function calendar-goto-today "cal-move" ())
  3846. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3847. (defvar calc-embedded-close-formula)
  3848. (defvar calc-embedded-open-formula)
  3849. (declare-function cdlatex-tab "ext:cdlatex" ())
  3850. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3851. (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
  3852. (defvar font-lock-unfontify-region-function)
  3853. (declare-function iswitchb-read-buffer "iswitchb"
  3854. (prompt &optional default require-match start matches-set))
  3855. (defvar iswitchb-temp-buflist)
  3856. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3857. (defvar org-agenda-tags-todo-honor-ignore-options)
  3858. (declare-function org-agenda-skip "org-agenda" ())
  3859. (declare-function
  3860. org-agenda-format-item "org-agenda"
  3861. (extra txt &optional level category tags dotime noprefix remove-re habitp))
  3862. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3863. (declare-function org-agenda-change-all-lines "org-agenda"
  3864. (newhead hdmarker &optional fixface just-this))
  3865. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3866. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3867. (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
  3868. (beg end))
  3869. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3870. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3871. "org-agenda" (&optional end))
  3872. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3873. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3874. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3875. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3876. (declare-function org-indent-mode "org-indent" (&optional arg))
  3877. (declare-function parse-time-string "parse-time" (string))
  3878. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3879. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3880. (defvar remember-data-file)
  3881. (defvar texmathp-why)
  3882. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3883. (declare-function table--at-cell-p "table" (position &optional object at-column))
  3884. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3885. ;;;###autoload
  3886. (defun turn-on-orgtbl ()
  3887. "Unconditionally turn on `orgtbl-mode'."
  3888. (require 'org-table)
  3889. (orgtbl-mode 1))
  3890. (defun org-at-table-p (&optional table-type)
  3891. "Non-nil if the cursor is inside an Org table.
  3892. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3893. If `org-enable-table-editor' is nil, return nil unconditionally."
  3894. (and
  3895. org-enable-table-editor
  3896. (save-excursion
  3897. (beginning-of-line)
  3898. (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3899. (or (not (derived-mode-p 'org-mode))
  3900. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3901. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3902. (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
  3903. (defun org-at-table.el-p ()
  3904. "Non-nil when point is at a table.el table."
  3905. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3906. (let ((element (org-element-at-point)))
  3907. (and (eq (org-element-type element) 'table)
  3908. (eq (org-element-property :type element) 'table.el)))))
  3909. (defun org-table-recognize-table.el ()
  3910. "If there is a table.el table nearby, recognize it and move into it."
  3911. (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
  3912. (beginning-of-line)
  3913. (unless (or (looking-at org-table-dataline-regexp)
  3914. (not (looking-at org-table1-hline-regexp)))
  3915. (forward-line)
  3916. (when (looking-at org-table-any-border-regexp)
  3917. (forward-line -2)))
  3918. (if (re-search-forward "|" (org-table-end t) t)
  3919. (progn
  3920. (require 'table)
  3921. (if (table--at-cell-p (point)) t
  3922. (message "recognizing table.el table...")
  3923. (table-recognize-table)
  3924. (message "recognizing table.el table...done")))
  3925. (error "This should not happen"))))
  3926. ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
  3927. (make-obsolete 'org-table-recognize-table.el
  3928. "please notify the org mailing list if you use this function."
  3929. "Org 9.0")
  3930. (defun org-at-table-hline-p ()
  3931. "Non-nil when point is inside a hline in a table.
  3932. Assume point is already in a table. If `org-enable-table-editor'
  3933. is nil, return nil unconditionally."
  3934. (and org-enable-table-editor
  3935. (save-excursion
  3936. (beginning-of-line)
  3937. (looking-at org-table-hline-regexp))))
  3938. (defun org-table-map-tables (function &optional quietly)
  3939. "Apply FUNCTION to the start of all tables in the buffer."
  3940. (save-excursion
  3941. (save-restriction
  3942. (widen)
  3943. (goto-char (point-min))
  3944. (while (re-search-forward org-table-any-line-regexp nil t)
  3945. (unless quietly
  3946. (message "Mapping tables: %d%%"
  3947. (floor (* 100.0 (point)) (buffer-size))))
  3948. (beginning-of-line 1)
  3949. (when (and (looking-at org-table-line-regexp)
  3950. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3951. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3952. (save-excursion (funcall function))
  3953. (or (looking-at org-table-line-regexp)
  3954. (forward-char 1)))
  3955. (re-search-forward org-table-any-border-regexp nil 1))))
  3956. (unless quietly (message "Mapping tables: done")))
  3957. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3958. (declare-function org-clock-update-mode-line "org-clock" ())
  3959. (declare-function org-resolve-clocks "org-clock"
  3960. (&optional also-non-dangling-p prompt last-valid))
  3961. (defun org-at-TBLFM-p (&optional pos)
  3962. "Non-nil when point (or POS) is in #+TBLFM line."
  3963. (save-excursion
  3964. (goto-char (or pos (point)))
  3965. (beginning-of-line)
  3966. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3967. (eq (org-element-type (org-element-at-point)) 'table))))
  3968. (defvar org-clock-start-time)
  3969. (defvar org-clock-marker (make-marker)
  3970. "Marker recording the last clock-in.")
  3971. (defvar org-clock-hd-marker (make-marker)
  3972. "Marker recording the last clock-in, but the headline position.")
  3973. (defvar org-clock-heading ""
  3974. "The heading of the current clock entry.")
  3975. (defun org-clock-is-active ()
  3976. "Return the buffer where the clock is currently running.
  3977. Return nil if no clock is running."
  3978. (marker-buffer org-clock-marker))
  3979. (defun org-check-running-clock ()
  3980. "Check if the current buffer contains the running clock.
  3981. If yes, offer to stop it and to save the buffer with the changes."
  3982. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3983. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3984. (buffer-name))))
  3985. (org-clock-out)
  3986. (when (y-or-n-p "Save changed buffer?")
  3987. (save-buffer))))
  3988. (defun org-clocktable-try-shift (dir n)
  3989. "Check if this line starts a clock table, if yes, shift the time block."
  3990. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3991. (org-clocktable-shift dir n)))
  3992. ;;;###autoload
  3993. (defun org-clock-persistence-insinuate ()
  3994. "Set up hooks for clock persistence."
  3995. (require 'org-clock)
  3996. (add-hook 'org-mode-hook 'org-clock-load)
  3997. (add-hook 'kill-emacs-hook 'org-clock-save))
  3998. (defgroup org-archive nil
  3999. "Options concerning archiving in Org-mode."
  4000. :tag "Org Archive"
  4001. :group 'org-structure)
  4002. (defcustom org-archive-location "%s_archive::"
  4003. "The location where subtrees should be archived.
  4004. The value of this variable is a string, consisting of two parts,
  4005. separated by a double-colon. The first part is a filename and
  4006. the second part is a headline.
  4007. When the filename is omitted, archiving happens in the same file.
  4008. %s in the filename will be replaced by the current file
  4009. name (without the directory part). Archiving to a different file
  4010. is useful to keep archived entries from contributing to the
  4011. Org-mode Agenda.
  4012. The archived entries will be filed as subtrees of the specified
  4013. headline. When the headline is omitted, the subtrees are simply
  4014. filed away at the end of the file, as top-level entries. Also in
  4015. the heading you can use %s to represent the file name, this can be
  4016. useful when using the same archive for a number of different files.
  4017. Here are a few examples:
  4018. \"%s_archive::\"
  4019. If the current file is Projects.org, archive in file
  4020. Projects.org_archive, as top-level trees. This is the default.
  4021. \"::* Archived Tasks\"
  4022. Archive in the current file, under the top-level headline
  4023. \"* Archived Tasks\".
  4024. \"~/org/archive.org::\"
  4025. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4026. \"~/org/archive.org::* From %s\"
  4027. Archive in file ~/org/archive.org (absolute path), under headlines
  4028. \"From FILENAME\" where file name is the current file name.
  4029. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4030. The \"datetree/\" string is special, signifying to archive
  4031. items to the datetree. Items are placed in either the CLOSED
  4032. date of the item, or the current date if there is no CLOSED date.
  4033. The heading will be a subentry to the current date. There doesn't
  4034. need to be a heading, but there always needs to be a slash after
  4035. datetree. For example, to store archived items directly in the
  4036. datetree, use \"~/org/datetree.org::datetree/\".
  4037. \"basement::** Finished Tasks\"
  4038. Archive in file ./basement (relative path), as level 3 trees
  4039. below the level 2 heading \"** Finished Tasks\".
  4040. You may set this option on a per-file basis by adding to the buffer a
  4041. line like
  4042. #+ARCHIVE: basement::** Finished Tasks
  4043. You may also define it locally for a subtree by setting an ARCHIVE property
  4044. in the entry. If such a property is found in an entry, or anywhere up
  4045. the hierarchy, it will be used."
  4046. :group 'org-archive
  4047. :type 'string)
  4048. (defcustom org-agenda-skip-archived-trees t
  4049. "Non-nil means the agenda will skip any items located in archived trees.
  4050. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4051. variable is no longer recommended, you should leave it at the value t.
  4052. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4053. :group 'org-archive
  4054. :group 'org-agenda-skip
  4055. :type 'boolean)
  4056. (defcustom org-columns-skip-archived-trees t
  4057. "Non-nil means ignore archived trees when creating column view."
  4058. :group 'org-archive
  4059. :group 'org-properties
  4060. :type 'boolean)
  4061. (defcustom org-cycle-open-archived-trees nil
  4062. "Non-nil means `org-cycle' will open archived trees.
  4063. An archived tree is a tree marked with the tag ARCHIVE.
  4064. When nil, archived trees will stay folded. You can still open them with
  4065. normal outline commands like `show-all', but not with the cycling commands."
  4066. :group 'org-archive
  4067. :group 'org-cycle
  4068. :type 'boolean)
  4069. (defcustom org-sparse-tree-open-archived-trees nil
  4070. "Non-nil means sparse tree construction shows matches in archived trees.
  4071. When nil, matches in these trees are highlighted, but the trees are kept in
  4072. collapsed state."
  4073. :group 'org-archive
  4074. :group 'org-sparse-trees
  4075. :type 'boolean)
  4076. (defcustom org-sparse-tree-default-date-type nil
  4077. "The default date type when building a sparse tree.
  4078. When this is nil, a date is a scheduled or a deadline timestamp.
  4079. Otherwise, these types are allowed:
  4080. all: all timestamps
  4081. active: only active timestamps (<...>)
  4082. inactive: only inactive timestamps ([...])
  4083. scheduled: only scheduled timestamps
  4084. deadline: only deadline timestamps"
  4085. :type '(choice (const :tag "Scheduled or deadline" nil)
  4086. (const :tag "All timestamps" all)
  4087. (const :tag "Only active timestamps" active)
  4088. (const :tag "Only inactive timestamps" inactive)
  4089. (const :tag "Only scheduled timestamps" scheduled)
  4090. (const :tag "Only deadline timestamps" deadline)
  4091. (const :tag "Only closed timestamps" closed))
  4092. :version "25.1"
  4093. :package-version '(Org . "8.3")
  4094. :group 'org-sparse-trees)
  4095. (defun org-cycle-hide-archived-subtrees (state)
  4096. "Re-hide all archived subtrees after a visibility state change."
  4097. (when (and (not org-cycle-open-archived-trees)
  4098. (not (memq state '(overview folded))))
  4099. (save-excursion
  4100. (let* ((globalp (memq state '(contents all)))
  4101. (beg (if globalp (point-min) (point)))
  4102. (end (if globalp (point-max) (org-end-of-subtree t))))
  4103. (org-hide-archived-subtrees beg end)
  4104. (goto-char beg)
  4105. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4106. (message "%s" (substitute-command-keys
  4107. "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
  4108. (defun org-force-cycle-archived ()
  4109. "Cycle subtree even if it is archived."
  4110. (interactive)
  4111. (setq this-command 'org-cycle)
  4112. (let ((org-cycle-open-archived-trees t))
  4113. (call-interactively 'org-cycle)))
  4114. (defun org-hide-archived-subtrees (beg end)
  4115. "Re-hide all archived subtrees after a visibility state change."
  4116. (org-with-wide-buffer
  4117. (let ((case-fold-search nil)
  4118. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4119. (goto-char beg)
  4120. ;; Include headline point is currently on.
  4121. (beginning-of-line)
  4122. (while (and (< (point) end) (re-search-forward re end t))
  4123. (when (member org-archive-tag (org-get-tags))
  4124. (org-flag-subtree t)
  4125. (org-end-of-subtree t))))))
  4126. (declare-function outline-end-of-heading "outline" ())
  4127. (declare-function outline-flag-region "outline" (from to flag))
  4128. (defun org-flag-subtree (flag)
  4129. (save-excursion
  4130. (org-back-to-heading t)
  4131. (outline-end-of-heading)
  4132. (outline-flag-region (point)
  4133. (progn (org-end-of-subtree t) (point))
  4134. flag)))
  4135. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4136. ;; Declare Column View Code
  4137. (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
  4138. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4139. (declare-function org-columns-compute "org-colview" (property))
  4140. ;; Declare ID code
  4141. (declare-function org-id-store-link "org-id")
  4142. (declare-function org-id-locations-load "org-id")
  4143. (declare-function org-id-locations-save "org-id")
  4144. (defvar org-id-track-globally)
  4145. ;;; Variables for pre-computed regular expressions, all buffer local
  4146. (defvar-local org-todo-regexp nil
  4147. "Matches any of the TODO state keywords.")
  4148. (defvar-local org-not-done-regexp nil
  4149. "Matches any of the TODO state keywords except the last one.")
  4150. (defvar-local org-not-done-heading-regexp nil
  4151. "Matches a TODO headline that is not done.")
  4152. (defvar-local org-todo-line-regexp nil
  4153. "Matches a headline and puts TODO state into group 2 if present.")
  4154. (defvar-local org-complex-heading-regexp nil
  4155. "Matches a headline and puts everything into groups:
  4156. group 1: the stars
  4157. group 2: The todo keyword, maybe
  4158. group 3: Priority cookie
  4159. group 4: True headline
  4160. group 5: Tags")
  4161. (defvar-local org-complex-heading-regexp-format nil
  4162. "Printf format to make regexp to match an exact headline.
  4163. This regexp will match the headline of any node which has the
  4164. exact headline text that is put into the format, but may have any
  4165. TODO state, priority and tags.")
  4166. (defvar-local org-todo-line-tags-regexp nil
  4167. "Matches a headline and puts TODO state into group 2 if present.
  4168. Also put tags into group 4 if tags are present.")
  4169. (defconst org-plain-time-of-day-regexp
  4170. (concat
  4171. "\\(\\<[012]?[0-9]"
  4172. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4173. "\\(--?"
  4174. "\\(\\<[012]?[0-9]"
  4175. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4176. "\\)?")
  4177. "Regular expression to match a plain time or time range.
  4178. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4179. groups carry important information:
  4180. 0 the full match
  4181. 1 the first time, range or not
  4182. 8 the second time, if it is a range.")
  4183. (defconst org-plain-time-extension-regexp
  4184. (concat
  4185. "\\(\\<[012]?[0-9]"
  4186. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4187. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4188. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4189. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4190. groups carry important information:
  4191. 0 the full match
  4192. 7 hours of duration
  4193. 9 minutes of duration")
  4194. (defconst org-stamp-time-of-day-regexp
  4195. (concat
  4196. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4197. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4198. "\\(--?"
  4199. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4200. "Regular expression to match a timestamp time or time range.
  4201. After a match, the following groups carry important information:
  4202. 0 the full match
  4203. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4204. 2 the first time, range or not
  4205. 4 the second time, if it is a range.")
  4206. (defconst org-startup-options
  4207. '(("fold" org-startup-folded t)
  4208. ("overview" org-startup-folded t)
  4209. ("nofold" org-startup-folded nil)
  4210. ("showall" org-startup-folded nil)
  4211. ("showeverything" org-startup-folded showeverything)
  4212. ("content" org-startup-folded content)
  4213. ("indent" org-startup-indented t)
  4214. ("noindent" org-startup-indented nil)
  4215. ("hidestars" org-hide-leading-stars t)
  4216. ("showstars" org-hide-leading-stars nil)
  4217. ("odd" org-odd-levels-only t)
  4218. ("oddeven" org-odd-levels-only nil)
  4219. ("align" org-startup-align-all-tables t)
  4220. ("noalign" org-startup-align-all-tables nil)
  4221. ("inlineimages" org-startup-with-inline-images t)
  4222. ("noinlineimages" org-startup-with-inline-images nil)
  4223. ("latexpreview" org-startup-with-latex-preview t)
  4224. ("nolatexpreview" org-startup-with-latex-preview nil)
  4225. ("customtime" org-display-custom-times t)
  4226. ("logdone" org-log-done time)
  4227. ("lognotedone" org-log-done note)
  4228. ("nologdone" org-log-done nil)
  4229. ("lognoteclock-out" org-log-note-clock-out t)
  4230. ("nolognoteclock-out" org-log-note-clock-out nil)
  4231. ("logrepeat" org-log-repeat state)
  4232. ("lognoterepeat" org-log-repeat note)
  4233. ("logdrawer" org-log-into-drawer t)
  4234. ("nologdrawer" org-log-into-drawer nil)
  4235. ("logstatesreversed" org-log-states-order-reversed t)
  4236. ("nologstatesreversed" org-log-states-order-reversed nil)
  4237. ("nologrepeat" org-log-repeat nil)
  4238. ("logreschedule" org-log-reschedule time)
  4239. ("lognotereschedule" org-log-reschedule note)
  4240. ("nologreschedule" org-log-reschedule nil)
  4241. ("logredeadline" org-log-redeadline time)
  4242. ("lognoteredeadline" org-log-redeadline note)
  4243. ("nologredeadline" org-log-redeadline nil)
  4244. ("logrefile" org-log-refile time)
  4245. ("lognoterefile" org-log-refile note)
  4246. ("nologrefile" org-log-refile nil)
  4247. ("fninline" org-footnote-define-inline t)
  4248. ("nofninline" org-footnote-define-inline nil)
  4249. ("fnlocal" org-footnote-section nil)
  4250. ("fnauto" org-footnote-auto-label t)
  4251. ("fnprompt" org-footnote-auto-label nil)
  4252. ("fnconfirm" org-footnote-auto-label confirm)
  4253. ("fnplain" org-footnote-auto-label plain)
  4254. ("fnadjust" org-footnote-auto-adjust t)
  4255. ("nofnadjust" org-footnote-auto-adjust nil)
  4256. ("constcgs" constants-unit-system cgs)
  4257. ("constSI" constants-unit-system SI)
  4258. ("noptag" org-tag-persistent-alist nil)
  4259. ("hideblocks" org-hide-block-startup t)
  4260. ("nohideblocks" org-hide-block-startup nil)
  4261. ("beamer" org-startup-with-beamer-mode t)
  4262. ("entitiespretty" org-pretty-entities t)
  4263. ("entitiesplain" org-pretty-entities nil))
  4264. "Variable associated with STARTUP options for org-mode.
  4265. Each element is a list of three items: the startup options (as written
  4266. in the #+STARTUP line), the corresponding variable, and the value to set
  4267. this variable to if the option is found. An optional forth element PUSH
  4268. means to push this value onto the list in the variable.")
  4269. (defcustom org-group-tags t
  4270. "When non-nil (the default), use group tags.
  4271. This can be turned on/off through `org-toggle-tags-groups'."
  4272. :group 'org-tags
  4273. :group 'org-startup
  4274. :type 'boolean)
  4275. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4276. (defun org-toggle-tags-groups ()
  4277. "Toggle support for group tags.
  4278. Support for group tags is controlled by the option
  4279. `org-group-tags', which is non-nil by default."
  4280. (interactive)
  4281. (setq org-group-tags (not org-group-tags))
  4282. (cond ((and (derived-mode-p 'org-agenda-mode)
  4283. org-group-tags)
  4284. (org-agenda-redo))
  4285. ((derived-mode-p 'org-mode)
  4286. (let ((org-inhibit-startup t)) (org-mode))))
  4287. (message "Groups tags support has been turned %s"
  4288. (if org-group-tags "on" "off")))
  4289. (defun org-set-regexps-and-options (&optional tags-only)
  4290. "Precompute regular expressions used in the current buffer.
  4291. When optional argument TAGS-ONLY is non-nil, only compute tags
  4292. related expressions."
  4293. (when (derived-mode-p 'org-mode)
  4294. (let ((alist (org--setup-collect-keywords
  4295. (org-make-options-regexp
  4296. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4297. (and (not tags-only)
  4298. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4299. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4300. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4301. (org--setup-process-tags
  4302. (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
  4303. (unless tags-only
  4304. ;; File properties.
  4305. (setq-local org-file-properties (cdr (assq 'property alist)))
  4306. ;; Archive location.
  4307. (let ((archive (cdr (assq 'archive alist))))
  4308. (when archive (setq-local org-archive-location archive)))
  4309. ;; Category.
  4310. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4311. (when cat
  4312. (setq-local org-category (intern cat))
  4313. (setq-local org-file-properties
  4314. (org--update-property-plist
  4315. "CATEGORY" cat org-file-properties))))
  4316. ;; Columns.
  4317. (let ((column (cdr (assq 'columns alist))))
  4318. (when column (setq-local org-columns-default-format column)))
  4319. ;; Constants.
  4320. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4321. ;; Link abbreviations.
  4322. (let ((links (cdr (assq 'link alist))))
  4323. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4324. ;; Priorities.
  4325. (let ((priorities (cdr (assq 'priorities alist))))
  4326. (when priorities
  4327. (setq-local org-highest-priority (nth 0 priorities))
  4328. (setq-local org-lowest-priority (nth 1 priorities))
  4329. (setq-local org-default-priority (nth 2 priorities))))
  4330. ;; Scripts.
  4331. (let ((scripts (assq 'scripts alist)))
  4332. (when scripts
  4333. (setq-local org-use-sub-superscripts (cdr scripts))))
  4334. ;; Startup options.
  4335. (let ((startup (cdr (assq 'startup alist))))
  4336. (dolist (option startup)
  4337. (let ((entry (assoc-string option org-startup-options t)))
  4338. (when entry
  4339. (let ((var (nth 1 entry))
  4340. (val (nth 2 entry)))
  4341. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4342. (unless (listp (symbol-value var))
  4343. (set (make-local-variable var) nil))
  4344. (add-to-list var val)))))))
  4345. ;; TODO keywords.
  4346. (setq-local org-todo-kwd-alist nil)
  4347. (setq-local org-todo-key-alist nil)
  4348. (setq-local org-todo-key-trigger nil)
  4349. (setq-local org-todo-keywords-1 nil)
  4350. (setq-local org-done-keywords nil)
  4351. (setq-local org-todo-heads nil)
  4352. (setq-local org-todo-sets nil)
  4353. (setq-local org-todo-log-states nil)
  4354. (let ((todo-sequences
  4355. (or (nreverse (cdr (assq 'todo alist)))
  4356. (let ((d (default-value 'org-todo-keywords)))
  4357. (if (not (stringp (car d))) d
  4358. ;; XXX: Backward compatibility code.
  4359. (list (cons org-todo-interpretation d)))))))
  4360. (dolist (sequence todo-sequences)
  4361. (let* ((sequence (or (run-hook-with-args-until-success
  4362. 'org-todo-setup-filter-hook sequence)
  4363. sequence))
  4364. (sequence-type (car sequence))
  4365. (keywords (cdr sequence))
  4366. (sep (member "|" keywords))
  4367. names alist)
  4368. (dolist (k (remove "|" keywords))
  4369. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4370. k)
  4371. (error "Invalid TODO keyword %s" k))
  4372. (let ((name (match-string 1 k))
  4373. (key (match-string 2 k))
  4374. (log (org-extract-log-state-settings k)))
  4375. (push name names)
  4376. (push (cons name (and key (string-to-char key))) alist)
  4377. (when log (push log org-todo-log-states))))
  4378. (let* ((names (nreverse names))
  4379. (done (if sep (org-remove-keyword-keys (cdr sep))
  4380. (last names)))
  4381. (head (car names))
  4382. (tail (list sequence-type head (car done) (org-last done))))
  4383. (add-to-list 'org-todo-heads head 'append)
  4384. (push names org-todo-sets)
  4385. (setq org-done-keywords (append org-done-keywords done nil))
  4386. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4387. (setq org-todo-key-alist
  4388. (append org-todo-key-alist
  4389. (and alist
  4390. (append '((:startgroup))
  4391. (nreverse alist)
  4392. '((:endgroup))))))
  4393. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4394. (setq org-todo-sets (nreverse org-todo-sets)
  4395. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4396. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4397. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4398. ;; Compute the regular expressions and other local variables.
  4399. ;; Using `org-outline-regexp-bol' would complicate them much,
  4400. ;; because of the fixed white space at the end of that string.
  4401. (unless org-done-keywords
  4402. (setq org-done-keywords
  4403. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4404. (setq org-not-done-keywords
  4405. (org-delete-all org-done-keywords
  4406. (copy-sequence org-todo-keywords-1))
  4407. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4408. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4409. org-not-done-heading-regexp
  4410. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4411. org-todo-line-regexp
  4412. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4413. org-complex-heading-regexp
  4414. (concat "^\\(\\*+\\)"
  4415. "\\(?: +" org-todo-regexp "\\)?"
  4416. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4417. "\\(?: +\\(.*?\\)\\)??"
  4418. (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
  4419. "[ \t]*$")
  4420. org-complex-heading-regexp-format
  4421. (concat "^\\(\\*+\\)"
  4422. "\\(?: +" org-todo-regexp "\\)?"
  4423. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4424. "\\(?: +"
  4425. ;; Stats cookies can be stuck to body.
  4426. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4427. "\\(%s\\)"
  4428. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4429. "\\)"
  4430. (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
  4431. "[ \t]*$")
  4432. org-todo-line-tags-regexp
  4433. (concat "^\\(\\*+\\)"
  4434. "\\(?: +" org-todo-regexp "\\)?"
  4435. "\\(?: +\\(.*?\\)\\)??"
  4436. (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
  4437. "[ \t]*$"))
  4438. (org-compute-latex-and-related-regexp)))))
  4439. (defun org--setup-collect-keywords (regexp &optional files alist)
  4440. "Return setup keywords values as an alist.
  4441. REGEXP matches a subset of setup keywords. FILES is a list of
  4442. file names already visited. It is used to avoid circular setup
  4443. files. ALIST, when non-nil, is the alist computed so far.
  4444. Return value contains the following keys: `archive', `category',
  4445. `columns', `constants', `filetags', `link', `priorities',
  4446. `property', `scripts', `startup', `tags' and `todo'."
  4447. (org-with-wide-buffer
  4448. (goto-char (point-min))
  4449. (let ((case-fold-search t))
  4450. (while (re-search-forward regexp nil t)
  4451. (let ((element (org-element-at-point)))
  4452. (when (eq (org-element-type element) 'keyword)
  4453. (let ((key (org-element-property :key element))
  4454. (value (org-element-property :value element)))
  4455. (cond
  4456. ((equal key "ARCHIVE")
  4457. (when (org-string-nw-p value)
  4458. (push (cons 'archive value) alist)))
  4459. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4460. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4461. ((equal key "CONSTANTS")
  4462. (let* ((constants (assq 'constants alist))
  4463. (store (cdr constants)))
  4464. (dolist (pair (org-split-string value))
  4465. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4466. pair)
  4467. (let* ((name (match-string 1 pair))
  4468. (value (match-string 2 pair))
  4469. (old (assoc name store)))
  4470. (if old (setcdr old value)
  4471. (push (cons name value) store)))))
  4472. (if constants (setcdr constants store)
  4473. (push (cons 'constants store) alist))))
  4474. ((equal key "FILETAGS")
  4475. (when (org-string-nw-p value)
  4476. (let ((old (assq 'filetags alist))
  4477. (new (apply #'nconc
  4478. (mapcar (lambda (x) (org-split-string x ":"))
  4479. (org-split-string value)))))
  4480. (if old (setcdr old (append new (cdr old)))
  4481. (push (cons 'filetags new) alist)))))
  4482. ((equal key "LINK")
  4483. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4484. (let ((links (assq 'link alist))
  4485. (pair (cons (org-match-string-no-properties 1 value)
  4486. (org-match-string-no-properties 2 value))))
  4487. (if links (push pair (cdr links))
  4488. (push (list 'link pair) alist)))))
  4489. ((equal key "OPTIONS")
  4490. (when (and (org-string-nw-p value)
  4491. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4492. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4493. ((equal key "PRIORITIES")
  4494. (push (cons 'priorities
  4495. (let ((prio (org-split-string value)))
  4496. (if (< (length prio) 3) '(?A ?C ?B)
  4497. (mapcar #'string-to-char prio))))
  4498. alist))
  4499. ((equal key "PROPERTY")
  4500. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4501. (let* ((property (assq 'property alist))
  4502. (value (org--update-property-plist
  4503. (org-match-string-no-properties 1 value)
  4504. (org-match-string-no-properties 2 value)
  4505. (cdr property))))
  4506. (if property (setcdr property value)
  4507. (push (cons 'property value) alist)))))
  4508. ((equal key "STARTUP")
  4509. (let ((startup (assq 'startup alist)))
  4510. (if startup
  4511. (setcdr startup
  4512. (append (cdr startup) (org-split-string value)))
  4513. (push (cons 'startup (org-split-string value)) alist))))
  4514. ((equal key "TAGS")
  4515. (let ((tag-cell (assq 'tags alist)))
  4516. (if tag-cell
  4517. (setcdr tag-cell
  4518. (append (cdr tag-cell)
  4519. '("\\n")
  4520. (org-split-string value)))
  4521. (push (cons 'tags (org-split-string value)) alist))))
  4522. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4523. (let ((todo (assq 'todo alist))
  4524. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4525. (org-split-string value))))
  4526. (if todo (push value (cdr todo))
  4527. (push (list 'todo value) alist))))
  4528. ((equal key "SETUPFILE")
  4529. (unless buffer-read-only ; Do not check in Gnus messages.
  4530. (let ((f (and (org-string-nw-p value)
  4531. (expand-file-name
  4532. (org-remove-double-quotes value)))))
  4533. (when (and f (file-readable-p f) (not (member f files)))
  4534. (with-temp-buffer
  4535. (setq default-directory (file-name-directory f))
  4536. (insert-file-contents f)
  4537. (setq alist
  4538. ;; Fake Org mode to benefit from cache
  4539. ;; without recurring needlessly.
  4540. (let ((major-mode 'org-mode))
  4541. (org--setup-collect-keywords
  4542. regexp (cons f files) alist)))))))))))))))
  4543. alist)
  4544. (defun org--setup-process-tags (tags filetags)
  4545. "Precompute variables used for tags.
  4546. TAGS is a list of tags and tag group symbols, as strings.
  4547. FILETAGS is a list of tags, as strings."
  4548. ;; Process the file tags.
  4549. (setq-local org-file-tags
  4550. (mapcar #'org-add-prop-inherited filetags))
  4551. ;; Provide default tags if no local tags are found.
  4552. (when (and (not tags) org-tag-alist)
  4553. (setq tags
  4554. (mapcar (lambda (tag)
  4555. (case (car tag)
  4556. (:startgroup "{")
  4557. (:endgroup "}")
  4558. (:startgrouptag "[")
  4559. (:endgrouptag "]")
  4560. (:grouptags ":")
  4561. (:newline "\\n")
  4562. (otherwise (concat (car tag)
  4563. (and (characterp (cdr tag))
  4564. (format "(%c)" (cdr tag)))))))
  4565. org-tag-alist)))
  4566. ;; Process the tags.
  4567. (setq-local org-tag-groups-alist nil)
  4568. (setq-local org-tag-alist nil)
  4569. (let (group-flag)
  4570. (while tags
  4571. (let ((e (car tags)))
  4572. (setq tags (cdr tags))
  4573. (cond
  4574. ((equal e "{")
  4575. (push '(:startgroup) org-tag-alist)
  4576. (when (equal (nth 1 tags) ":") (setq group-flag t)))
  4577. ((equal e "}")
  4578. (push '(:endgroup) org-tag-alist)
  4579. (setq group-flag nil))
  4580. ((equal e "[")
  4581. (push '(:startgrouptag) org-tag-alist)
  4582. (when (equal (nth 1 tags) ":") (setq group-flag t)))
  4583. ((equal e "]")
  4584. (push '(:endgrouptag) org-tag-alist)
  4585. (setq group-flag nil))
  4586. ((equal e ":")
  4587. (push '(:grouptags) org-tag-alist)
  4588. (setq group-flag 'append))
  4589. ((equal e "\\n") (push '(:newline) org-tag-alist))
  4590. ((string-match
  4591. (org-re (concat "\\`\\([[:alnum:]_@#%]+"
  4592. "\\|{.+?}\\)" ; regular expression
  4593. "\\(?:(\\(.\\))\\)?\\'")) e)
  4594. (let ((tag (match-string 1 e))
  4595. (key (and (match-beginning 2)
  4596. (string-to-char (match-string 2 e)))))
  4597. (cond ((eq group-flag 'append)
  4598. (setcar org-tag-groups-alist
  4599. (append (car org-tag-groups-alist) (list tag))))
  4600. (group-flag (push (list tag) org-tag-groups-alist)))
  4601. ;; Push all tags in groups, no matter if they already exist.
  4602. (unless (and (not group-flag) (assoc tag org-tag-alist))
  4603. (push (cons tag key) org-tag-alist))))))))
  4604. (setq org-tag-alist (nreverse org-tag-alist)))
  4605. (defun org-file-contents (file &optional noerror)
  4606. "Return the contents of FILE, as a string."
  4607. (if (and file (file-readable-p file))
  4608. (with-temp-buffer
  4609. (insert-file-contents file)
  4610. (buffer-string))
  4611. (funcall (if noerror 'message 'error)
  4612. "Cannot read file \"%s\"%s"
  4613. file
  4614. (let ((from (buffer-file-name (buffer-base-buffer))))
  4615. (if from (concat " (referenced in file \"" from "\")") "")))))
  4616. (defun org-extract-log-state-settings (x)
  4617. "Extract the log state setting from a TODO keyword string.
  4618. This will extract info from a string like \"WAIT(w@/!)\"."
  4619. (let (kw key log1 log2)
  4620. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4621. (setq kw (match-string 1 x)
  4622. key (and (match-end 2) (match-string 2 x))
  4623. log1 (and (match-end 3) (match-string 3 x))
  4624. log2 (and (match-end 4) (match-string 4 x)))
  4625. (and (or log1 log2)
  4626. (list kw
  4627. (and log1 (if (equal log1 "!") 'time 'note))
  4628. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4629. (defun org-remove-keyword-keys (list)
  4630. "Remove a pair of parenthesis at the end of each string in LIST."
  4631. (mapcar (lambda (x)
  4632. (if (string-match "(.*)$" x)
  4633. (substring x 0 (match-beginning 0))
  4634. x))
  4635. list))
  4636. (defun org-assign-fast-keys (alist)
  4637. "Assign fast keys to a keyword-key alist.
  4638. Respect keys that are already there."
  4639. (let (new e (alt ?0))
  4640. (while (setq e (pop alist))
  4641. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4642. (cdr e)) ;; Key already assigned.
  4643. (push e new)
  4644. (let ((clist (string-to-list (downcase (car e))))
  4645. (used (append new alist)))
  4646. (when (= (car clist) ?@)
  4647. (pop clist))
  4648. (while (and clist (rassoc (car clist) used))
  4649. (pop clist))
  4650. (unless clist
  4651. (while (rassoc alt used)
  4652. (incf alt)))
  4653. (push (cons (car e) (or (car clist) alt)) new))))
  4654. (nreverse new)))
  4655. ;;; Some variables used in various places
  4656. (defvar org-window-configuration nil
  4657. "Used in various places to store a window configuration.")
  4658. (defvar org-selected-window nil
  4659. "Used in various places to store a window configuration.")
  4660. (defvar org-finish-function nil
  4661. "Function to be called when `C-c C-c' is used.
  4662. This is for getting out of special buffers like capture.")
  4663. ;; FIXME: Occasionally check by commenting these, to make sure
  4664. ;; no other functions uses these, forgetting to let-bind them.
  4665. (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
  4666. (defvar org-last-state)
  4667. (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
  4668. ;; Defined somewhere in this file, but used before definition.
  4669. (defvar org-entities) ;; defined in org-entities.el
  4670. (defvar org-struct-menu)
  4671. (defvar org-org-menu)
  4672. (defvar org-tbl-menu)
  4673. ;;;; Define the Org-mode
  4674. ;; We use a before-change function to check if a table might need
  4675. ;; an update.
  4676. (defvar org-table-may-need-update t
  4677. "Indicates that a table might need an update.
  4678. This variable is set by `org-before-change-function'.
  4679. `org-table-align' sets it back to nil.")
  4680. (defun org-before-change-function (beg end)
  4681. "Every change indicates that a table might need an update."
  4682. (setq org-table-may-need-update t))
  4683. (defvar org-mode-map)
  4684. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4685. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4686. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4687. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4688. (defvar org-table-buffer-is-an nil)
  4689. (defvar bidi-paragraph-direction)
  4690. (defvar buffer-face-mode-face)
  4691. (require 'outline)
  4692. (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
  4693. (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
  4694. (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
  4695. ;; Other stuff we need.
  4696. (require 'time-date)
  4697. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4698. (require 'easymenu)
  4699. (autoload 'easy-menu-add "easymenu")
  4700. (require 'overlay)
  4701. ;; (require 'org-macs) moved higher up in the file before it is first used
  4702. (require 'org-entities)
  4703. ;; (require 'org-compat) moved higher up in the file before it is first used
  4704. (require 'org-faces)
  4705. (require 'org-list)
  4706. (require 'org-pcomplete)
  4707. (require 'org-src)
  4708. (require 'org-footnote)
  4709. (require 'org-macro)
  4710. ;; babel
  4711. (require 'ob)
  4712. ;;;###autoload
  4713. (define-derived-mode org-mode outline-mode "Org"
  4714. "Outline-based notes management and organizer, alias
  4715. \"Carsten's outline-mode for keeping track of everything.\"
  4716. Org-mode develops organizational tasks around a NOTES file which
  4717. contains information about projects as plain text. Org-mode is
  4718. implemented on top of outline-mode, which is ideal to keep the content
  4719. of large files well structured. It supports ToDo items, deadlines and
  4720. time stamps, which magically appear in the diary listing of the Emacs
  4721. calendar. Tables are easily created with a built-in table editor.
  4722. Plain text URL-like links connect to websites, emails (VM), Usenet
  4723. messages (Gnus), BBDB entries, and any files related to the project.
  4724. For printing and sharing of notes, an Org-mode file (or a part of it)
  4725. can be exported as a structured ASCII or HTML file.
  4726. The following commands are available:
  4727. \\{org-mode-map}"
  4728. ;; Get rid of Outline menus, they are not needed
  4729. ;; Need to do this here because define-derived-mode sets up
  4730. ;; the keymap so late. Still, it is a waste to call this each time
  4731. ;; we switch another buffer into org-mode.
  4732. (if (featurep 'xemacs)
  4733. (when (boundp 'outline-mode-menu-heading)
  4734. ;; Assume this is Greg's port, it uses easymenu
  4735. (easy-menu-remove outline-mode-menu-heading)
  4736. (easy-menu-remove outline-mode-menu-show)
  4737. (easy-menu-remove outline-mode-menu-hide))
  4738. (define-key org-mode-map [menu-bar headings] 'undefined)
  4739. (define-key org-mode-map [menu-bar hide] 'undefined)
  4740. (define-key org-mode-map [menu-bar show] 'undefined))
  4741. (org-load-modules-maybe)
  4742. (when (featurep 'xemacs)
  4743. (easy-menu-add org-org-menu)
  4744. (easy-menu-add org-tbl-menu))
  4745. (org-install-agenda-files-menu)
  4746. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4747. (add-to-invisibility-spec '(org-cwidth))
  4748. (add-to-invisibility-spec '(org-hide-block . t))
  4749. (when (featurep 'xemacs)
  4750. (setq-local line-move-ignore-invisible t))
  4751. (setq-local outline-regexp org-outline-regexp)
  4752. (setq-local outline-level 'org-outline-level)
  4753. (setq bidi-paragraph-direction 'left-to-right)
  4754. (when (and org-ellipsis
  4755. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4756. (fboundp 'make-glyph-code))
  4757. (unless org-display-table
  4758. (setq org-display-table (make-display-table)))
  4759. (set-display-table-slot
  4760. org-display-table 4
  4761. (vconcat (mapcar
  4762. (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
  4763. org-ellipsis)))
  4764. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4765. (setq buffer-display-table org-display-table))
  4766. (org-set-regexps-and-options)
  4767. (org-set-font-lock-defaults)
  4768. (when (and org-tag-faces (not org-tags-special-faces-re))
  4769. ;; tag faces set outside customize.... force initialization.
  4770. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4771. ;; Calc embedded
  4772. (setq-local calc-embedded-open-mode "# ")
  4773. ;; Modify a few syntax entries
  4774. (modify-syntax-entry ?@ "w")
  4775. (modify-syntax-entry ?\" "\"")
  4776. (modify-syntax-entry ?\\ "_")
  4777. (modify-syntax-entry ?~ "_")
  4778. (when org-startup-truncated (setq truncate-lines t))
  4779. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4780. (setq-local font-lock-unfontify-region-function
  4781. 'org-unfontify-region)
  4782. ;; Activate before-change-function
  4783. (setq-local org-table-may-need-update t)
  4784. (org-add-hook 'before-change-functions 'org-before-change-function nil
  4785. 'local)
  4786. ;; Check for running clock before killing a buffer
  4787. (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4788. ;; Initialize macros templates.
  4789. (org-macro-initialize-templates)
  4790. ;; Initialize radio targets.
  4791. (org-update-radio-target-regexp)
  4792. ;; Indentation.
  4793. (setq-local indent-line-function 'org-indent-line)
  4794. (setq-local indent-region-function 'org-indent-region)
  4795. ;; Filling and auto-filling.
  4796. (org-setup-filling)
  4797. ;; Comments.
  4798. (org-setup-comments-handling)
  4799. ;; Initialize cache.
  4800. (org-element-cache-reset)
  4801. ;; Beginning/end of defun
  4802. (setq-local beginning-of-defun-function 'org-backward-element)
  4803. (setq-local end-of-defun-function
  4804. (lambda ()
  4805. (if (not (org-at-heading-p))
  4806. (org-forward-element)
  4807. (org-forward-element)
  4808. (forward-char -1))))
  4809. ;; Next error for sparse trees
  4810. (setq-local next-error-function 'org-occur-next-match)
  4811. ;; Make sure dependence stuff works reliably, even for users who set it
  4812. ;; too late :-(
  4813. (if org-enforce-todo-dependencies
  4814. (add-hook 'org-blocker-hook
  4815. 'org-block-todo-from-children-or-siblings-or-parent)
  4816. (remove-hook 'org-blocker-hook
  4817. 'org-block-todo-from-children-or-siblings-or-parent))
  4818. (if org-enforce-todo-checkbox-dependencies
  4819. (add-hook 'org-blocker-hook
  4820. 'org-block-todo-from-checkboxes)
  4821. (remove-hook 'org-blocker-hook
  4822. 'org-block-todo-from-checkboxes))
  4823. ;; Align options lines
  4824. (setq-local
  4825. align-mode-rules-list
  4826. '((org-in-buffer-settings
  4827. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4828. (modes . '(org-mode)))))
  4829. ;; Imenu
  4830. (setq-local imenu-create-index-function
  4831. 'org-imenu-get-tree)
  4832. ;; Make isearch reveal context
  4833. (if (or (featurep 'xemacs)
  4834. (not (boundp 'outline-isearch-open-invisible-function)))
  4835. ;; Emacs 21 and XEmacs make use of the hook
  4836. (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
  4837. ;; Emacs 22 deals with this through a special variable
  4838. (setq-local outline-isearch-open-invisible-function
  4839. (lambda (&rest ignore) (org-show-context 'isearch))))
  4840. ;; Setup the pcomplete hooks
  4841. (setq-local pcomplete-command-completion-function
  4842. 'org-pcomplete-initial)
  4843. (setq-local pcomplete-command-name-function
  4844. 'org-command-at-point)
  4845. (setq-local pcomplete-default-completion-function
  4846. 'ignore)
  4847. (setq-local pcomplete-parse-arguments-function
  4848. 'org-parse-arguments)
  4849. (setq-local pcomplete-termination-string "")
  4850. (setq-local buffer-face-mode-face 'org-default)
  4851. ;; If empty file that did not turn on org-mode automatically, make it to.
  4852. (when (and org-insert-mode-line-in-empty-file
  4853. (org-called-interactively-p 'any)
  4854. (= (point-min) (point-max)))
  4855. (insert "# -*- mode: org -*-\n\n"))
  4856. (unless org-inhibit-startup
  4857. (org-unmodified
  4858. (and org-startup-with-beamer-mode (org-beamer-mode))
  4859. (when org-startup-align-all-tables
  4860. (org-table-map-tables 'org-table-align 'quietly))
  4861. (when org-startup-with-inline-images
  4862. (org-display-inline-images))
  4863. (when org-startup-with-latex-preview
  4864. (org-toggle-latex-fragment))
  4865. (unless org-inhibit-startup-visibility-stuff
  4866. (org-set-startup-visibility))
  4867. (org-refresh-effort-properties)))
  4868. ;; Try to set org-hide correctly
  4869. (let ((foreground (org-find-invisible-foreground)))
  4870. (when foreground
  4871. (set-face-foreground 'org-hide foreground))))
  4872. ;; Update `customize-package-emacs-version-alist'
  4873. (add-to-list 'customize-package-emacs-version-alist
  4874. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4875. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4876. ("8.2.6" . "24.4") ("8.3" . "25.1")))
  4877. (defvar org-mode-transpose-word-syntax-table
  4878. (let ((st (make-syntax-table text-mode-syntax-table)))
  4879. (mapc (lambda(c) (modify-syntax-entry
  4880. (string-to-char (car c)) "w p" st))
  4881. org-emphasis-alist)
  4882. st))
  4883. (when (fboundp 'abbrev-table-put)
  4884. (abbrev-table-put org-mode-abbrev-table
  4885. :parents (list text-mode-abbrev-table)))
  4886. (defun org-find-invisible-foreground ()
  4887. (let ((candidates (remove
  4888. "unspecified-bg"
  4889. (nconc
  4890. (list (face-background 'default)
  4891. (face-background 'org-default))
  4892. (mapcar
  4893. (lambda (alist)
  4894. (when (boundp alist)
  4895. (cdr (assoc 'background-color (symbol-value alist)))))
  4896. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4897. (list (face-foreground 'org-hide))))))
  4898. (car (remove nil candidates))))
  4899. (defun org-current-time (&optional rounding-minutes past)
  4900. "Current time, possibly rounded to ROUNDING-MINUTES.
  4901. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4902. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4903. the rounding returns a past time."
  4904. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4905. (car org-time-stamp-rounding-minutes)))
  4906. (time (decode-time)) res)
  4907. (if (< r 1)
  4908. (current-time)
  4909. (setq res
  4910. (apply 'encode-time
  4911. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4912. (nthcdr 2 time))))
  4913. (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
  4914. (seconds-to-time (- (org-float-time res) (* r 60)))
  4915. res))))
  4916. (defun org-today ()
  4917. "Return today date, considering `org-extend-today-until'."
  4918. (time-to-days
  4919. (time-subtract (current-time)
  4920. (list 0 (* 3600 org-extend-today-until) 0))))
  4921. ;;;; Font-Lock stuff, including the activators
  4922. (defvar org-mouse-map (make-sparse-keymap))
  4923. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4924. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4925. (when org-mouse-1-follows-link
  4926. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4927. (when org-tab-follows-link
  4928. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4929. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4930. (require 'font-lock)
  4931. (defconst org-non-link-chars "]\t\n\r<>")
  4932. (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
  4933. "file+sys" "news" "shell" "elisp" "doi" "message"
  4934. "help"))
  4935. (defvar org-link-types-re nil
  4936. "Matches a link that has a url-like prefix like \"http:\"")
  4937. (defvar org-link-re-with-space nil
  4938. "Matches a link with spaces, optional angular brackets around it.")
  4939. (defvar org-link-re-with-space2 nil
  4940. "Matches a link with spaces, optional angular brackets around it.")
  4941. (defvar org-link-re-with-space3 nil
  4942. "Matches a link with spaces, only for internal part in bracket links.")
  4943. (defvar org-angle-link-re nil
  4944. "Matches link with angular brackets, spaces are allowed.")
  4945. (defvar org-plain-link-re nil
  4946. "Matches plain link, without spaces.")
  4947. (defvar org-bracket-link-regexp nil
  4948. "Matches a link in double brackets.")
  4949. (defvar org-bracket-link-analytic-regexp nil
  4950. "Regular expression used to analyze links.
  4951. Here is what the match groups contain after a match:
  4952. 1: http:
  4953. 2: http
  4954. 3: path
  4955. 4: [desc]
  4956. 5: desc")
  4957. (defvar org-bracket-link-analytic-regexp++ nil
  4958. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4959. (defvar org-any-link-re nil
  4960. "Regular expression matching any link.")
  4961. (defconst org-match-sexp-depth 3
  4962. "Number of stacked braces for sub/superscript matching.")
  4963. (defun org-create-multibrace-regexp (left right n)
  4964. "Create a regular expression which will match a balanced sexp.
  4965. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4966. as single character strings.
  4967. The regexp returned will match the entire expression including the
  4968. delimiters. It will also define a single group which contains the
  4969. match except for the outermost delimiters. The maximum depth of
  4970. stacked delimiters is N. Escaping delimiters is not possible."
  4971. (let* ((nothing (concat "[^" left right "]*?"))
  4972. (or "\\|")
  4973. (re nothing)
  4974. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4975. (while (> n 1)
  4976. (setq n (1- n)
  4977. re (concat re or next)
  4978. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4979. (concat left "\\(" re "\\)" right)))
  4980. (defconst org-match-substring-regexp
  4981. (concat
  4982. "\\(\\S-\\)\\([_^]\\)\\("
  4983. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4984. "\\|"
  4985. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4986. "\\|"
  4987. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4988. "The regular expression matching a sub- or superscript.")
  4989. (defconst org-match-substring-with-braces-regexp
  4990. (concat
  4991. "\\(\\S-\\)\\([_^]\\)"
  4992. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4993. "The regular expression matching a sub- or superscript, forcing braces.")
  4994. (defun org-make-link-regexps ()
  4995. "Update the link regular expressions.
  4996. This should be called after the variable `org-link-types' has changed."
  4997. (let ((types-re (regexp-opt org-link-types t)))
  4998. (setq org-link-types-re
  4999. (concat "\\`" types-re ":")
  5000. org-link-re-with-space
  5001. (concat "<?" types-re ":"
  5002. "\\([^" org-non-link-chars " ]"
  5003. "[^" org-non-link-chars "]*"
  5004. "[^" org-non-link-chars " ]\\)>?")
  5005. org-link-re-with-space2
  5006. (concat "<?" types-re ":"
  5007. "\\([^" org-non-link-chars " ]"
  5008. "[^\t\n\r]*"
  5009. "[^" org-non-link-chars " ]\\)>?")
  5010. org-link-re-with-space3
  5011. (concat "<?" types-re ":"
  5012. "\\([^" org-non-link-chars " ]"
  5013. "[^\t\n\r]*\\)")
  5014. org-angle-link-re
  5015. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5016. types-re)
  5017. org-plain-link-re
  5018. (concat
  5019. "\\<" types-re ":"
  5020. (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
  5021. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5022. org-bracket-link-regexp
  5023. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5024. org-bracket-link-analytic-regexp
  5025. (concat
  5026. "\\[\\["
  5027. "\\(" types-re ":\\)?"
  5028. "\\([^]]+\\)"
  5029. "\\]"
  5030. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5031. "\\]")
  5032. org-bracket-link-analytic-regexp++
  5033. (concat
  5034. "\\[\\["
  5035. "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
  5036. "\\([^]]+\\)"
  5037. "\\]"
  5038. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5039. "\\]")
  5040. org-any-link-re
  5041. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5042. org-angle-link-re "\\)\\|\\("
  5043. org-plain-link-re "\\)"))))
  5044. (org-make-link-regexps)
  5045. (defvar org-emph-face nil)
  5046. (defun org-do-emphasis-faces (limit)
  5047. "Run through the buffer and emphasize strings."
  5048. (let (rtn a)
  5049. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5050. (let* ((border (char-after (match-beginning 3)))
  5051. (bre (regexp-quote (char-to-string border))))
  5052. (when (and (not (= border (char-after (match-beginning 4))))
  5053. (not (string-match-p (concat bre ".*" bre)
  5054. (replace-regexp-in-string
  5055. "\n" " "
  5056. (substring (match-string 2) 1 -1)))))
  5057. (setq rtn t)
  5058. (setq a (assoc (match-string 3) org-emphasis-alist))
  5059. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5060. 'face
  5061. (nth 1 a))
  5062. (and (nth 2 a)
  5063. (org-remove-flyspell-overlays-in
  5064. (match-beginning 0) (match-end 0)))
  5065. (add-text-properties (match-beginning 2) (match-end 2)
  5066. '(font-lock-multiline t org-emphasis t))
  5067. (when org-hide-emphasis-markers
  5068. (add-text-properties (match-end 4) (match-beginning 5)
  5069. '(invisible org-link))
  5070. (add-text-properties (match-beginning 3) (match-end 3)
  5071. '(invisible org-link)))))
  5072. (goto-char (1+ (match-beginning 0))))
  5073. rtn))
  5074. (defun org-emphasize (&optional char)
  5075. "Insert or change an emphasis, i.e. a font like bold or italic.
  5076. If there is an active region, change that region to a new emphasis.
  5077. If there is no region, just insert the marker characters and position
  5078. the cursor between them.
  5079. CHAR should be the marker character. If it is a space, it means to
  5080. remove the emphasis of the selected region.
  5081. If CHAR is not given (for example in an interactive call) it will be
  5082. prompted for."
  5083. (interactive)
  5084. (let ((erc org-emphasis-regexp-components)
  5085. (prompt "")
  5086. (string "") beg end move c s)
  5087. (if (org-region-active-p)
  5088. (setq beg (region-beginning) end (region-end)
  5089. string (buffer-substring beg end))
  5090. (setq move t))
  5091. (unless char
  5092. (message "Emphasis marker or tag: [%s]"
  5093. (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
  5094. (setq char (read-char-exclusive)))
  5095. (if (equal char ?\ )
  5096. (setq s "" move nil)
  5097. (unless (assoc (char-to-string char) org-emphasis-alist)
  5098. (user-error "No such emphasis marker: \"%c\"" char))
  5099. (setq s (char-to-string char)))
  5100. (while (and (> (length string) 1)
  5101. (equal (substring string 0 1) (substring string -1))
  5102. (assoc (substring string 0 1) org-emphasis-alist))
  5103. (setq string (substring string 1 -1)))
  5104. (setq string (concat s string s))
  5105. (when beg (delete-region beg end))
  5106. (unless (or (bolp)
  5107. (string-match (concat "[" (nth 0 erc) "\n]")
  5108. (char-to-string (char-before (point)))))
  5109. (insert " "))
  5110. (unless (or (eobp)
  5111. (string-match (concat "[" (nth 1 erc) "\n]")
  5112. (char-to-string (char-after (point)))))
  5113. (insert " ") (backward-char 1))
  5114. (insert string)
  5115. (and move (backward-char 1))))
  5116. (defconst org-nonsticky-props
  5117. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5118. (defsubst org-rear-nonsticky-at (pos)
  5119. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5120. (defun org-activate-plain-links (limit)
  5121. "Add link properties for plain links."
  5122. (let (f hl)
  5123. (when (and (re-search-forward (concat org-plain-link-re) limit t)
  5124. (not (member 'org-tag
  5125. (get-text-property (1- (match-beginning 0)) 'face)))
  5126. (not (org-in-src-block-p)))
  5127. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5128. (setq f (get-text-property (match-beginning 0) 'face))
  5129. (setq hl (org-match-string-no-properties 0))
  5130. (unless (or (eq f 'org-tag)
  5131. (and (listp f) (memq 'org-tag f)))
  5132. (add-text-properties (match-beginning 0) (match-end 0)
  5133. (list 'mouse-face 'highlight
  5134. 'face 'org-link
  5135. 'htmlize-link `(:uri ,hl)
  5136. 'keymap org-mouse-map))
  5137. (org-rear-nonsticky-at (match-end 0)))
  5138. t)))
  5139. (defun org-activate-code (limit)
  5140. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5141. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5142. (remove-text-properties (match-beginning 0) (match-end 0)
  5143. '(display t invisible t intangible t))
  5144. t))
  5145. (defcustom org-src-fontify-natively t
  5146. "When non-nil, fontify code in code blocks."
  5147. :type 'boolean
  5148. :version "24.4"
  5149. :package-version '(Org . "8.3")
  5150. :group 'org-appearance
  5151. :group 'org-babel)
  5152. (defcustom org-allow-promoting-top-level-subtree nil
  5153. "When non-nil, allow promoting a top level subtree.
  5154. The leading star of the top level headline will be replaced
  5155. by a #."
  5156. :type 'boolean
  5157. :version "24.1"
  5158. :group 'org-appearance)
  5159. (defun org-fontify-meta-lines-and-blocks (limit)
  5160. (condition-case nil
  5161. (org-fontify-meta-lines-and-blocks-1 limit)
  5162. (error (message "org-mode fontification error"))))
  5163. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5164. "Fontify #+ lines and blocks."
  5165. (let ((case-fold-search t))
  5166. (when (re-search-forward
  5167. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5168. limit t)
  5169. (let ((beg (match-beginning 0))
  5170. (block-start (match-end 0))
  5171. (block-end nil)
  5172. (lang (match-string 7))
  5173. (beg1 (line-beginning-position 2))
  5174. (dc1 (downcase (match-string 2)))
  5175. (dc3 (downcase (match-string 3)))
  5176. end end1 quoting block-type ovl)
  5177. (cond
  5178. ((and (match-end 4) (equal dc3 "+begin"))
  5179. ;; Truly a block
  5180. (setq block-type (downcase (match-string 5))
  5181. quoting (member block-type org-protecting-blocks))
  5182. (when (re-search-forward
  5183. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5184. nil t) ;; on purpose, we look further than LIMIT
  5185. (setq end (min (point-max) (match-end 0))
  5186. end1 (min (point-max) (1- (match-beginning 0))))
  5187. (setq block-end (match-beginning 0))
  5188. (when quoting
  5189. (org-remove-flyspell-overlays-in beg1 end1)
  5190. (remove-text-properties beg end
  5191. '(display t invisible t intangible t)))
  5192. (add-text-properties
  5193. beg end '(font-lock-fontified t font-lock-multiline t))
  5194. (add-text-properties beg beg1 '(face org-meta-line))
  5195. (org-remove-flyspell-overlays-in beg beg1)
  5196. (add-text-properties ; For end_src
  5197. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5198. (org-remove-flyspell-overlays-in end1 end)
  5199. (cond
  5200. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5201. (org-src-font-lock-fontify-block lang block-start block-end)
  5202. (add-text-properties beg1 block-end '(src-block t)))
  5203. (quoting
  5204. (add-text-properties beg1 (min (point-max) (1+ end1))
  5205. '(face org-block))) ; end of source block
  5206. ((not org-fontify-quote-and-verse-blocks))
  5207. ((string= block-type "quote")
  5208. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5209. ((string= block-type "verse")
  5210. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5211. (add-text-properties beg beg1 '(face org-block-begin-line))
  5212. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5213. '(face org-block-end-line))
  5214. t))
  5215. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5216. (org-remove-flyspell-overlays-in
  5217. (match-beginning 0)
  5218. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5219. (add-text-properties
  5220. beg (match-end 3)
  5221. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5222. '(font-lock-fontified t invisible t)
  5223. '(font-lock-fontified t face org-document-info-keyword)))
  5224. (add-text-properties
  5225. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5226. (if (string-equal dc1 "+title:")
  5227. '(font-lock-fontified t face org-document-title)
  5228. '(font-lock-fontified t face org-document-info))))
  5229. ((equal dc1 "+caption:")
  5230. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5231. (remove-text-properties (match-beginning 0) (match-end 0)
  5232. '(display t invisible t intangible t))
  5233. (add-text-properties (match-beginning 1) (match-end 3)
  5234. '(font-lock-fontified t face org-meta-line))
  5235. (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
  5236. '(font-lock-fontified t face org-block))
  5237. t)
  5238. ((member dc3 '(" " ""))
  5239. (org-remove-flyspell-overlays-in beg (match-end 0))
  5240. (add-text-properties
  5241. beg (match-end 0)
  5242. '(font-lock-fontified t face font-lock-comment-face)))
  5243. (t ;; just any other in-buffer setting, but not indented
  5244. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5245. (remove-text-properties (match-beginning 0) (match-end 0)
  5246. '(display t invisible t intangible t))
  5247. (add-text-properties beg (match-end 0)
  5248. '(font-lock-fontified t face org-meta-line))
  5249. t))))))
  5250. (defun org-fontify-drawers (limit)
  5251. "Fontify drawers."
  5252. (when (re-search-forward org-drawer-regexp limit t)
  5253. (add-text-properties
  5254. (match-beginning 0) (match-end 0)
  5255. '(font-lock-fontified t face org-special-keyword))
  5256. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5257. t))
  5258. (defun org-fontify-macros (limit)
  5259. "Fontify macros."
  5260. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5261. (add-text-properties
  5262. (match-beginning 0) (match-end 0)
  5263. '(font-lock-fontified t face org-macro))
  5264. (when org-hide-macro-markers
  5265. (add-text-properties (match-end 2) (match-beginning 2)
  5266. '(invisible t))
  5267. (add-text-properties (match-beginning 1) (match-end 1)
  5268. '(invisible t)))
  5269. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5270. t))
  5271. (defun org-activate-angle-links (limit)
  5272. "Add text properties for angle links."
  5273. (when (and (re-search-forward org-angle-link-re limit t)
  5274. (not (org-in-src-block-p)))
  5275. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5276. (add-text-properties (match-beginning 0) (match-end 0)
  5277. (list 'mouse-face 'highlight
  5278. 'keymap org-mouse-map
  5279. 'font-lock-multiline t))
  5280. (org-rear-nonsticky-at (match-end 0))
  5281. t))
  5282. (defun org-activate-footnote-links (limit)
  5283. "Add text properties for footnotes."
  5284. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5285. (when fn
  5286. (let* ((beg (nth 1 fn))
  5287. (end (nth 2 fn))
  5288. (label (car fn))
  5289. (referencep (/= (line-beginning-position) beg)))
  5290. (when (and referencep (nth 3 fn))
  5291. (save-excursion
  5292. (goto-char beg)
  5293. (search-forward (or label "fn:"))
  5294. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5295. (add-text-properties beg end
  5296. (list 'mouse-face 'highlight
  5297. 'keymap org-mouse-map
  5298. 'help-echo
  5299. (if referencep "Footnote reference"
  5300. "Footnote definition")
  5301. 'font-lock-fontified t
  5302. 'font-lock-multiline t
  5303. 'face 'org-footnote))))))
  5304. (defun org-activate-bracket-links (limit)
  5305. "Add text properties for bracketed links."
  5306. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5307. (not (org-in-src-block-p)))
  5308. (let* ((hl (org-match-string-no-properties 1))
  5309. (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
  5310. (ip (org-maybe-intangible
  5311. (list 'invisible 'org-link
  5312. 'keymap org-mouse-map 'mouse-face 'highlight
  5313. 'font-lock-multiline t 'help-echo help
  5314. 'htmlize-link `(:uri ,hl))))
  5315. (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
  5316. 'font-lock-multiline t 'help-echo help
  5317. 'htmlize-link `(:uri ,hl))))
  5318. ;; We need to remove the invisible property here. Table narrowing
  5319. ;; may have made some of this invisible.
  5320. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5321. (remove-text-properties (match-beginning 0) (match-end 0)
  5322. '(invisible nil))
  5323. (if (match-end 3)
  5324. (progn
  5325. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5326. (org-rear-nonsticky-at (match-beginning 3))
  5327. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5328. (org-rear-nonsticky-at (match-end 3))
  5329. (add-text-properties (match-end 3) (match-end 0) ip)
  5330. (org-rear-nonsticky-at (match-end 0)))
  5331. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5332. (org-rear-nonsticky-at (match-beginning 1))
  5333. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5334. (org-rear-nonsticky-at (match-end 1))
  5335. (add-text-properties (match-end 1) (match-end 0) ip)
  5336. (org-rear-nonsticky-at (match-end 0)))
  5337. t)))
  5338. (defun org-activate-dates (limit)
  5339. "Add text properties for dates."
  5340. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5341. (not (equal (char-before (match-beginning 0)) 91)))
  5342. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5343. (add-text-properties (match-beginning 0) (match-end 0)
  5344. (list 'mouse-face 'highlight
  5345. 'keymap org-mouse-map))
  5346. (org-rear-nonsticky-at (match-end 0))
  5347. (when org-display-custom-times
  5348. (if (match-end 3)
  5349. (org-display-custom-time (match-beginning 3) (match-end 3))
  5350. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5351. t))
  5352. (defvar-local org-target-link-regexp nil
  5353. "Regular expression matching radio targets in plain text.")
  5354. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5355. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5356. border border border))
  5357. "Regular expression matching a link target.")
  5358. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5359. "Regular expression matching a radio target.")
  5360. (defconst org-any-target-regexp
  5361. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5362. "Regular expression matching any target.")
  5363. (defun org-activate-target-links (limit)
  5364. "Add text properties for target matches."
  5365. (when org-target-link-regexp
  5366. (let ((case-fold-search t))
  5367. (when (re-search-forward org-target-link-regexp limit t)
  5368. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5369. (add-text-properties (match-beginning 1) (match-end 1)
  5370. (list 'mouse-face 'highlight
  5371. 'keymap org-mouse-map
  5372. 'help-echo "Radio target link"
  5373. 'org-linked-text t))
  5374. (org-rear-nonsticky-at (match-end 1))
  5375. t))))
  5376. (defun org-update-radio-target-regexp ()
  5377. "Find all radio targets in this file and update the regular expression.
  5378. Also refresh fontification if needed."
  5379. (interactive)
  5380. (let ((old-regexp org-target-link-regexp)
  5381. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5382. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5383. (targets
  5384. (org-with-wide-buffer
  5385. (goto-char (point-min))
  5386. (let (rtn)
  5387. (while (re-search-forward org-radio-target-regexp nil t)
  5388. ;; Make sure point is really within the object.
  5389. (backward-char)
  5390. (let ((obj (org-element-context)))
  5391. (when (eq (org-element-type obj) 'radio-target)
  5392. (add-to-list 'rtn (org-element-property :value obj)))))
  5393. rtn))))
  5394. (setq org-target-link-regexp
  5395. (and targets
  5396. (concat before-re
  5397. (mapconcat
  5398. (lambda (x)
  5399. (replace-regexp-in-string
  5400. " +" "\\s-+" (regexp-quote x) t t))
  5401. targets
  5402. "\\|")
  5403. after-re)))
  5404. (unless (equal old-regexp org-target-link-regexp)
  5405. ;; Clean-up cache.
  5406. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5407. ((not org-target-link-regexp) old-regexp)
  5408. (t
  5409. (concat before-re
  5410. (mapconcat
  5411. (lambda (re)
  5412. (substring re (length before-re)
  5413. (- (length after-re))))
  5414. (list old-regexp org-target-link-regexp)
  5415. "\\|")
  5416. after-re)))))
  5417. (org-with-wide-buffer
  5418. (goto-char (point-min))
  5419. (while (re-search-forward regexp nil t)
  5420. (org-element-cache-refresh (match-beginning 1)))))
  5421. ;; Re fontify buffer.
  5422. (when (memq 'radio org-highlight-links)
  5423. (org-restart-font-lock)))))
  5424. (defun org-hide-wide-columns (limit)
  5425. (let (s e)
  5426. (setq s (text-property-any (point) (or limit (point-max))
  5427. 'org-cwidth t))
  5428. (when s
  5429. (setq e (next-single-property-change s 'org-cwidth))
  5430. (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
  5431. (goto-char e)
  5432. t)))
  5433. (defvar org-latex-and-related-regexp nil
  5434. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5435. (defun org-compute-latex-and-related-regexp ()
  5436. "Compute regular expression for LaTeX, entities and sub/superscript.
  5437. Result depends on variable `org-highlight-latex-and-related'."
  5438. (setq-local
  5439. org-latex-and-related-regexp
  5440. (let* ((re-sub
  5441. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5442. ((eq org-use-sub-superscripts '{})
  5443. (list org-match-substring-with-braces-regexp))
  5444. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5445. (re-latex
  5446. (when (memq 'latex org-highlight-latex-and-related)
  5447. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5448. (delq nil
  5449. (mapcar (lambda (x)
  5450. (and (member (car x) matchers) (nth 1 x)))
  5451. org-latex-regexps)))))
  5452. (re-entities
  5453. (when (memq 'entities org-highlight-latex-and-related)
  5454. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5455. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5456. (defun org-do-latex-and-related (limit)
  5457. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5458. LIMIT bounds the search for syntax to highlight. Stop at first
  5459. highlighted object, if any. Return t if some highlighting was
  5460. done, nil otherwise."
  5461. (when (org-string-nw-p org-latex-and-related-regexp)
  5462. (catch 'found
  5463. (while (re-search-forward org-latex-and-related-regexp limit t)
  5464. (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
  5465. 'face))
  5466. '(org-code org-verbatim underline))
  5467. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5468. '(?_ ?^))
  5469. 1
  5470. 0)))
  5471. (font-lock-prepend-text-property
  5472. (+ offset (match-beginning 0)) (match-end 0)
  5473. 'face 'org-latex-and-related)
  5474. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5475. '(font-lock-multiline t)))
  5476. (throw 'found t)))
  5477. nil)))
  5478. (defun org-restart-font-lock ()
  5479. "Restart `font-lock-mode', to force refontification."
  5480. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5481. (font-lock-mode -1)
  5482. (font-lock-mode 1)))
  5483. (defun org-activate-tags (limit)
  5484. (when (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
  5485. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5486. (add-text-properties (match-beginning 1) (match-end 1)
  5487. (list 'mouse-face 'highlight
  5488. 'keymap org-mouse-map))
  5489. (org-rear-nonsticky-at (match-end 1))
  5490. t))
  5491. (defun org-outline-level ()
  5492. "Compute the outline level of the heading at point.
  5493. If this is called at a normal headline, the level is the number
  5494. of stars. Use `org-reduced-level' to remove the effect of
  5495. `org-odd-levels'. Unlike to `org-current-level', this function
  5496. takes into consideration inlinetasks."
  5497. (org-with-wide-buffer
  5498. (end-of-line)
  5499. (if (re-search-backward org-outline-regexp-bol nil t)
  5500. (1- (- (match-end 0) (match-beginning 0)))
  5501. 0)))
  5502. (defvar org-font-lock-keywords nil)
  5503. (defsubst org-re-property (property &optional literal allow-null value)
  5504. "Return a regexp matching a PROPERTY line.
  5505. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5506. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5507. non-nil, match properties even without a value.
  5508. Match group 3 is set to the value when it exists. If there is no
  5509. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5510. With optional argument VALUE, match only property lines with
  5511. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5512. unless LITERAL is non-nil."
  5513. (concat
  5514. "^\\(?4:[ \t]*\\)"
  5515. (format "\\(?1::\\(?2:%s\\):\\)"
  5516. (if literal property (regexp-quote property)))
  5517. (cond (value
  5518. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5519. (if literal value (regexp-quote value))))
  5520. (allow-null
  5521. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5522. (t
  5523. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5524. (defconst org-property-re
  5525. (org-re-property "\\S-+" 'literal t)
  5526. "Regular expression matching a property line.
  5527. There are four matching groups:
  5528. 1: :PROPKEY: including the leading and trailing colon,
  5529. 2: PROPKEY without the leading and trailing colon,
  5530. 3: PROPVAL without leading or trailing spaces,
  5531. 4: the indentation of the current line,
  5532. 5: trailing whitespace.")
  5533. (defvar org-font-lock-hook nil
  5534. "Functions to be called for special font lock stuff.")
  5535. (defvar org-font-lock-set-keywords-hook nil
  5536. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5537. This is called after `org-font-lock-extra-keywords' is defined, but before
  5538. it is installed to be used by font lock. This can be useful if something
  5539. needs to be inserted at a specific position in the font-lock sequence.")
  5540. (defun org-font-lock-hook (limit)
  5541. "Run `org-font-lock-hook' within LIMIT."
  5542. (run-hook-with-args 'org-font-lock-hook limit))
  5543. (defun org-set-font-lock-defaults ()
  5544. "Set font lock defaults for the current buffer."
  5545. (let* ((em org-fontify-emphasized-text)
  5546. (lk org-highlight-links)
  5547. (org-font-lock-extra-keywords
  5548. (list
  5549. ;; Call the hook
  5550. '(org-font-lock-hook)
  5551. ;; Headlines
  5552. `(,(if org-fontify-whole-heading-line
  5553. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5554. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5555. (1 (org-get-level-face 1))
  5556. (2 (org-get-level-face 2))
  5557. (3 (org-get-level-face 3)))
  5558. ;; Table lines
  5559. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5560. (1 'org-table t))
  5561. ;; Table internals
  5562. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5563. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5564. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5565. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5566. ;; Drawers
  5567. '(org-fontify-drawers)
  5568. ;; Properties
  5569. (list org-property-re
  5570. '(1 'org-special-keyword t)
  5571. '(3 'org-property-value t))
  5572. ;; Links
  5573. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5574. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5575. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
  5576. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
  5577. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5578. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5579. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5580. ;; Targets.
  5581. (list org-any-target-regexp '(0 'org-target t))
  5582. ;; Diary sexps.
  5583. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5584. ;; Macro
  5585. '(org-fontify-macros)
  5586. '(org-hide-wide-columns (0 nil append))
  5587. ;; TODO keyword
  5588. (list (format org-heading-keyword-regexp-format
  5589. org-todo-regexp)
  5590. '(2 (org-get-todo-face 2) t))
  5591. ;; DONE
  5592. (if org-fontify-done-headline
  5593. (list (format org-heading-keyword-regexp-format
  5594. (concat
  5595. "\\(?:"
  5596. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5597. "\\)"))
  5598. '(2 'org-headline-done t))
  5599. nil)
  5600. ;; Priorities
  5601. '(org-font-lock-add-priority-faces)
  5602. ;; Tags
  5603. '(org-font-lock-add-tag-faces)
  5604. ;; Tags groups
  5605. (when (and org-group-tags org-tag-groups-alist)
  5606. (list (concat org-outline-regexp-bol ".+\\(:"
  5607. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5608. ":\\).*$")
  5609. '(1 'org-tag-group prepend)))
  5610. ;; Special keywords
  5611. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5612. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5613. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5614. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5615. ;; Emphasis
  5616. (when em
  5617. (if (featurep 'xemacs)
  5618. '(org-do-emphasis-faces (0 nil append))
  5619. '(org-do-emphasis-faces)))
  5620. ;; Checkboxes
  5621. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5622. 1 'org-checkbox prepend)
  5623. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5624. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5625. (0 (org-get-checkbox-statistics-face) t)))
  5626. ;; Description list items
  5627. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5628. 1 'org-list-dt prepend)
  5629. ;; ARCHIVEd headings
  5630. (list (concat
  5631. org-outline-regexp-bol
  5632. "\\(.*:" org-archive-tag ":.*\\)")
  5633. '(1 'org-archived prepend))
  5634. ;; Specials
  5635. '(org-do-latex-and-related)
  5636. '(org-fontify-entities)
  5637. '(org-raise-scripts)
  5638. ;; Code
  5639. '(org-activate-code (1 'org-code t))
  5640. ;; COMMENT
  5641. (list (format
  5642. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5643. org-todo-regexp
  5644. org-comment-string)
  5645. '(9 'org-special-keyword t))
  5646. ;; Blocks and meta lines
  5647. '(org-fontify-meta-lines-and-blocks))))
  5648. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5649. (run-hooks 'org-font-lock-set-keywords-hook)
  5650. ;; Now set the full font-lock-keywords
  5651. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5652. (setq-local font-lock-defaults
  5653. '(org-font-lock-keywords t nil nil backward-paragraph))
  5654. (kill-local-variable 'font-lock-keywords) nil))
  5655. (defun org-toggle-pretty-entities ()
  5656. "Toggle the composition display of entities as UTF8 characters."
  5657. (interactive)
  5658. (setq-local org-pretty-entities (not org-pretty-entities))
  5659. (org-restart-font-lock)
  5660. (if org-pretty-entities
  5661. (message "Entities are now displayed as UTF8 characters")
  5662. (save-restriction
  5663. (widen)
  5664. (org-decompose-region (point-min) (point-max))
  5665. (message "Entities are now displayed as plain text"))))
  5666. (defvar-local org-custom-properties-overlays nil
  5667. "List of overlays used for custom properties.")
  5668. (defun org-toggle-custom-properties-visibility ()
  5669. "Display or hide properties in `org-custom-properties'."
  5670. (interactive)
  5671. (if org-custom-properties-overlays
  5672. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5673. (setq org-custom-properties-overlays nil))
  5674. (when org-custom-properties
  5675. (org-with-wide-buffer
  5676. (goto-char (point-min))
  5677. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5678. (while (re-search-forward regexp nil t)
  5679. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5680. (when (and end (< (point) end))
  5681. ;; Hide first custom property in current drawer.
  5682. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5683. (overlay-put o 'invisible t)
  5684. (overlay-put o 'org-custom-property t)
  5685. (push o org-custom-properties-overlays))
  5686. ;; Hide additional custom properties in the same drawer.
  5687. (while (re-search-forward regexp end t)
  5688. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5689. (overlay-put o 'invisible t)
  5690. (overlay-put o 'org-custom-property t)
  5691. (push o org-custom-properties-overlays)))))
  5692. ;; Each entry is limited to a single property drawer.
  5693. (outline-next-heading)))))))
  5694. (defun org-fontify-entities (limit)
  5695. "Find an entity to fontify."
  5696. (let (ee)
  5697. (when org-pretty-entities
  5698. (catch 'match
  5699. ;; "\_ "-family is left out on purpose. Only the first one,
  5700. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5701. ;; confusing when adding a second white space character.
  5702. (while (re-search-forward
  5703. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5704. limit t)
  5705. (when (and (not (org-at-comment-p))
  5706. (setq ee (org-entity-get (match-string 1)))
  5707. (= (length (nth 6 ee)) 1))
  5708. (let* ((end (if (equal (match-string 2) "{}")
  5709. (match-end 2)
  5710. (match-end 1))))
  5711. (add-text-properties
  5712. (match-beginning 0) end
  5713. (list 'font-lock-fontified t))
  5714. (compose-region (match-beginning 0) end
  5715. (nth 6 ee) nil)
  5716. (backward-char 1)
  5717. (throw 'match t))))
  5718. nil))))
  5719. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5720. "Fontify string S like in Org-mode."
  5721. (with-temp-buffer
  5722. (insert s)
  5723. (let ((org-odd-levels-only odd-levels))
  5724. (org-mode)
  5725. (font-lock-ensure)
  5726. (buffer-string))))
  5727. (defvar org-m nil)
  5728. (defvar org-l nil)
  5729. (defvar org-f nil)
  5730. (defun org-get-level-face (n)
  5731. "Get the right face for match N in font-lock matching of headlines."
  5732. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5733. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5734. (if org-cycle-level-faces
  5735. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5736. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5737. (cond
  5738. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5739. ((eq n 2) org-f)
  5740. (t (unless org-level-color-stars-only org-f))))
  5741. (defun org-face-from-face-or-color (context inherit face-or-color)
  5742. "Create a face list that inherits INHERIT, but sets the foreground color.
  5743. When FACE-OR-COLOR is not a string, just return it."
  5744. (if (stringp face-or-color)
  5745. (list :inherit inherit
  5746. (cdr (assoc context org-faces-easy-properties))
  5747. face-or-color)
  5748. face-or-color))
  5749. (defun org-get-todo-face (kwd)
  5750. "Get the right face for a TODO keyword KWD.
  5751. If KWD is a number, get the corresponding match group."
  5752. (when (numberp kwd) (setq kwd (match-string kwd)))
  5753. (or (org-face-from-face-or-color
  5754. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5755. (and (member kwd org-done-keywords) 'org-done)
  5756. 'org-todo))
  5757. (defun org-get-priority-face (priority)
  5758. "Get the right face for PRIORITY.
  5759. PRIORITY is a character."
  5760. (or (org-face-from-face-or-color
  5761. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5762. 'org-priority))
  5763. (defun org-get-tag-face (tag)
  5764. "Get the right face for TAG.
  5765. If TAG is a number, get the corresponding match group."
  5766. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5767. (or (org-face-from-face-or-color
  5768. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5769. 'org-tag)))
  5770. (defun org-font-lock-add-priority-faces (limit)
  5771. "Add the special priority faces."
  5772. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5773. (add-text-properties
  5774. (match-beginning 1) (match-end 1)
  5775. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5776. 'font-lock-fontified t))))
  5777. (defun org-font-lock-add-tag-faces (limit)
  5778. "Add the special tag faces."
  5779. (when (and org-tag-faces org-tags-special-faces-re)
  5780. (while (re-search-forward org-tags-special-faces-re limit t)
  5781. (add-text-properties (match-beginning 1) (match-end 1)
  5782. (list 'face (org-get-tag-face 1)
  5783. 'font-lock-fontified t))
  5784. (backward-char 1))))
  5785. (defun org-unfontify-region (beg end &optional maybe_loudly)
  5786. "Remove fontification and activation overlays from links."
  5787. (font-lock-default-unfontify-region beg end)
  5788. (let* ((buffer-undo-list t)
  5789. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5790. (inhibit-modification-hooks t)
  5791. deactivate-mark buffer-file-name buffer-file-truename)
  5792. (org-decompose-region beg end)
  5793. (remove-text-properties beg end
  5794. '(mouse-face t keymap t org-linked-text t
  5795. invisible t intangible t
  5796. org-emphasis t))
  5797. (org-remove-font-lock-display-properties beg end)))
  5798. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5799. ((raise 0.3) (height 0.7))
  5800. ((raise -0.5))
  5801. ((raise 0.5)))
  5802. "Display properties for showing superscripts and subscripts.")
  5803. (defun org-remove-font-lock-display-properties (beg end)
  5804. "Remove specific display properties that have been added by font lock.
  5805. The will remove the raise properties that are used to show superscripts
  5806. and subscripts."
  5807. (let (next prop)
  5808. (while (< beg end)
  5809. (setq next (next-single-property-change beg 'display nil end)
  5810. prop (get-text-property beg 'display))
  5811. (when (member prop org-script-display)
  5812. (put-text-property beg next 'display nil))
  5813. (setq beg next))))
  5814. (defun org-raise-scripts (limit)
  5815. "Add raise properties to sub/superscripts."
  5816. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5817. (re-search-forward
  5818. (if (eq org-use-sub-superscripts t)
  5819. org-match-substring-regexp
  5820. org-match-substring-with-braces-regexp)
  5821. limit t))
  5822. (let* ((pos (point)) table-p comment-p
  5823. (mpos (match-beginning 3))
  5824. (emph-p (get-text-property mpos 'org-emphasis))
  5825. (link-p (get-text-property mpos 'mouse-face))
  5826. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5827. (goto-char (point-at-bol))
  5828. (setq table-p (org-looking-at-p org-table-dataline-regexp)
  5829. comment-p (org-looking-at-p "^[ \t]*#[ +]"))
  5830. (goto-char pos)
  5831. ;; Handle a_b^c
  5832. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5833. (unless (or comment-p emph-p link-p keyw-p)
  5834. (put-text-property (match-beginning 3) (match-end 0)
  5835. 'display
  5836. (if (equal (char-after (match-beginning 2)) ?^)
  5837. (nth (if table-p 3 1) org-script-display)
  5838. (nth (if table-p 2 0) org-script-display)))
  5839. (add-text-properties (match-beginning 2) (match-end 2)
  5840. (list 'invisible t
  5841. 'org-dwidth t 'org-dwidth-n 1))
  5842. (if (and (eq (char-after (match-beginning 3)) ?{)
  5843. (eq (char-before (match-end 3)) ?}))
  5844. (progn
  5845. (add-text-properties
  5846. (match-beginning 3) (1+ (match-beginning 3))
  5847. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  5848. (add-text-properties
  5849. (1- (match-end 3)) (match-end 3)
  5850. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  5851. t)))
  5852. ;;;; Visibility cycling, including org-goto and indirect buffer
  5853. ;;; Cycling
  5854. (defvar-local org-cycle-global-status nil)
  5855. (put 'org-cycle-global-status 'org-state t)
  5856. (defvar-local org-cycle-subtree-status nil)
  5857. (put 'org-cycle-subtree-status 'org-state t)
  5858. (defvar org-inlinetask-min-level)
  5859. (defun org-unlogged-message (&rest args)
  5860. "Display a message, but avoid logging it in the *Messages* buffer."
  5861. (let ((message-log-max nil))
  5862. (apply 'message args)))
  5863. ;;;###autoload
  5864. (defun org-cycle (&optional arg)
  5865. "TAB-action and visibility cycling for Org-mode.
  5866. This is the command invoked in Org-mode by the TAB key. Its main purpose
  5867. is outline visibility cycling, but it also invokes other actions
  5868. in special contexts.
  5869. - When this function is called with a prefix argument, rotate the entire
  5870. buffer through 3 states (global cycling)
  5871. 1. OVERVIEW: Show only top-level headlines.
  5872. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5873. 3. SHOW ALL: Show everything.
  5874. With a double \\[universal-argument] prefix argument, \
  5875. switch to the startup visibility,
  5876. determined by the variable `org-startup-folded', and by any VISIBILITY
  5877. properties in the buffer.
  5878. With a triple \\[universal-argument] prefix argument, \
  5879. show the entire buffer, including any drawers.
  5880. - When inside a table, re-align the table and move to the next field.
  5881. - When point is at the beginning of a headline, rotate the subtree started
  5882. by this line through 3 different states (local cycling)
  5883. 1. FOLDED: Only the main headline is shown.
  5884. 2. CHILDREN: The main headline and the direct children are shown.
  5885. From this state, you can move to one of the children
  5886. and zoom in further.
  5887. 3. SUBTREE: Show the entire subtree, including body text.
  5888. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5889. - When point is at the beginning of an empty headline and the variable
  5890. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5891. of the headline by demoting and promoting it to likely levels. This
  5892. speeds up creation document structure by pressing TAB once or several
  5893. times right after creating a new headline.
  5894. - When there is a numeric prefix, go up to a heading with level ARG, do
  5895. a `show-subtree' and return to the previous cursor position. If ARG
  5896. is negative, go up that many levels.
  5897. - When point is not at the beginning of a headline, execute the global
  5898. binding for TAB, which is re-indenting the line. See the option
  5899. `org-cycle-emulate-tab' for details.
  5900. - Special case: if point is at the beginning of the buffer and there is
  5901. no headline in line 1, this function will act as if called with prefix arg
  5902. (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
  5903. But only if also the variable `org-cycle-global-at-bob' is t."
  5904. (interactive "P")
  5905. (org-load-modules-maybe)
  5906. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5907. (and org-cycle-level-after-item/entry-creation
  5908. (or (org-cycle-level)
  5909. (org-cycle-item-indentation))))
  5910. (let* ((limit-level
  5911. (or org-cycle-max-level
  5912. (and (boundp 'org-inlinetask-min-level)
  5913. org-inlinetask-min-level
  5914. (1- org-inlinetask-min-level))))
  5915. (nstars (and limit-level
  5916. (if org-odd-levels-only
  5917. (and limit-level (1- (* limit-level 2)))
  5918. limit-level)))
  5919. (org-outline-regexp
  5920. (if (not (derived-mode-p 'org-mode))
  5921. outline-regexp
  5922. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5923. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5924. (not (looking-at org-outline-regexp))))
  5925. (org-cycle-hook
  5926. (if bob-special
  5927. (delq 'org-optimize-window-after-visibility-change
  5928. (copy-sequence org-cycle-hook))
  5929. org-cycle-hook))
  5930. (pos (point)))
  5931. (when (or bob-special (equal arg '(4)))
  5932. ;; special case: use global cycling
  5933. (setq arg t))
  5934. (cond
  5935. ((equal arg '(16))
  5936. (setq last-command 'dummy)
  5937. (org-set-startup-visibility)
  5938. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5939. ((equal arg '(64))
  5940. (outline-show-all)
  5941. (org-unlogged-message "Entire buffer visible, including drawers"))
  5942. ;; Try cdlatex TAB completion
  5943. ((org-try-cdlatex-tab))
  5944. ;; Table: enter it or move to the next field.
  5945. ((org-at-table-p 'any)
  5946. (if (org-at-table.el-p)
  5947. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5948. Use \\[org-edit-special] to edit table.el tables"))
  5949. (if arg (org-table-edit-field t)
  5950. (org-table-justify-field-maybe)
  5951. (call-interactively 'org-table-next-field))))
  5952. ((run-hook-with-args-until-success
  5953. 'org-tab-after-check-for-table-hook))
  5954. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5955. ((eq arg t) (org-cycle-internal-global))
  5956. ;; Drawers: delegate to `org-flag-drawer'.
  5957. ((save-excursion
  5958. (beginning-of-line 1)
  5959. (looking-at org-drawer-regexp))
  5960. (org-flag-drawer ; toggle block visibility
  5961. (not (get-char-property (match-end 0) 'invisible))))
  5962. ;; Show-subtree, ARG levels up from here.
  5963. ((integerp arg)
  5964. (save-excursion
  5965. (org-back-to-heading)
  5966. (outline-up-heading (if (< arg 0) (- arg)
  5967. (- (funcall outline-level) arg)))
  5968. (org-show-subtree)))
  5969. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5970. ((and (featurep 'org-inlinetask)
  5971. (org-inlinetask-at-task-p)
  5972. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5973. (org-inlinetask-toggle-visibility))
  5974. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5975. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5976. (save-excursion (move-beginning-of-line 1)
  5977. (looking-at org-outline-regexp)))
  5978. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5979. (org-cycle-internal-local))
  5980. ;; From there: TAB emulation and template completion.
  5981. (buffer-read-only (org-back-to-heading))
  5982. ((run-hook-with-args-until-success
  5983. 'org-tab-after-check-for-cycling-hook))
  5984. ((org-try-structure-completion))
  5985. ((run-hook-with-args-until-success
  5986. 'org-tab-before-tab-emulation-hook))
  5987. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5988. (or (not (bolp))
  5989. (not (looking-at org-outline-regexp))))
  5990. (call-interactively (global-key-binding "\t")))
  5991. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5992. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5993. (or (and (eq org-cycle-emulate-tab 'white)
  5994. (= (match-end 0) (point-at-eol)))
  5995. (and (eq org-cycle-emulate-tab 'whitestart)
  5996. (>= (match-end 0) pos))))
  5997. t
  5998. (eq org-cycle-emulate-tab t))
  5999. (call-interactively (global-key-binding "\t")))
  6000. (t (save-excursion
  6001. (org-back-to-heading)
  6002. (org-cycle)))))))
  6003. (defun org-cycle-internal-global ()
  6004. "Do the global cycling action."
  6005. ;; Hack to avoid display of messages for .org attachments in Gnus
  6006. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6007. (cond
  6008. ((and (eq last-command this-command)
  6009. (eq org-cycle-global-status 'overview))
  6010. ;; We just created the overview - now do table of contents
  6011. ;; This can be slow in very large buffers, so indicate action
  6012. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6013. (unless ga (org-unlogged-message "CONTENTS..."))
  6014. (org-content)
  6015. (unless ga (org-unlogged-message "CONTENTS...done"))
  6016. (setq org-cycle-global-status 'contents)
  6017. (run-hook-with-args 'org-cycle-hook 'contents))
  6018. ((and (eq last-command this-command)
  6019. (eq org-cycle-global-status 'contents))
  6020. ;; We just showed the table of contents - now show everything
  6021. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6022. (outline-show-all)
  6023. (unless ga (org-unlogged-message "SHOW ALL"))
  6024. (setq org-cycle-global-status 'all)
  6025. (run-hook-with-args 'org-cycle-hook 'all))
  6026. (t
  6027. ;; Default action: go to overview
  6028. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6029. (org-overview)
  6030. (unless ga (org-unlogged-message "OVERVIEW"))
  6031. (setq org-cycle-global-status 'overview)
  6032. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6033. (defvar org-called-with-limited-levels nil
  6034. "Non-nil when `org-with-limited-levels' is currently active.")
  6035. (defun org-cycle-internal-local ()
  6036. "Do the local cycling action."
  6037. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6038. ;; First, determine end of headline (EOH), end of subtree or item
  6039. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6040. (save-excursion
  6041. (if (org-at-item-p)
  6042. (progn
  6043. (beginning-of-line)
  6044. (setq struct (org-list-struct))
  6045. (setq eoh (point-at-eol))
  6046. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6047. (setq has-children (org-list-has-child-p (point) struct)))
  6048. (org-back-to-heading)
  6049. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6050. (setq eos (save-excursion (org-end-of-subtree t t)
  6051. (when (bolp) (backward-char)) (point)))
  6052. (setq has-children
  6053. (or (save-excursion
  6054. (let ((level (funcall outline-level)))
  6055. (outline-next-heading)
  6056. (and (org-at-heading-p t)
  6057. (> (funcall outline-level) level))))
  6058. (save-excursion
  6059. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6060. ;; Determine end invisible part of buffer (EOL)
  6061. (beginning-of-line 2)
  6062. ;; XEmacs doesn't have `next-single-char-property-change'
  6063. (if (featurep 'xemacs)
  6064. (while (and (not (eobp)) ;; this is like `next-line'
  6065. (get-char-property (1- (point)) 'invisible))
  6066. (beginning-of-line 2))
  6067. (while (and (not (eobp)) ;; this is like `next-line'
  6068. (get-char-property (1- (point)) 'invisible))
  6069. (goto-char (next-single-char-property-change (point) 'invisible))
  6070. (and (eolp) (beginning-of-line 2))))
  6071. (setq eol (point)))
  6072. ;; Find out what to do next and set `this-command'
  6073. (cond
  6074. ((= eos eoh)
  6075. ;; Nothing is hidden behind this heading
  6076. (unless (org-before-first-heading-p)
  6077. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6078. (org-unlogged-message "EMPTY ENTRY")
  6079. (setq org-cycle-subtree-status nil)
  6080. (save-excursion
  6081. (goto-char eos)
  6082. (outline-next-heading)
  6083. (when (outline-invisible-p) (org-flag-heading nil))))
  6084. ((and (or (>= eol eos)
  6085. (not (string-match "\\S-" (buffer-substring eol eos))))
  6086. (or has-children
  6087. (not (setq children-skipped
  6088. org-cycle-skip-children-state-if-no-children))))
  6089. ;; Entire subtree is hidden in one line: children view
  6090. (unless (org-before-first-heading-p)
  6091. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6092. (if (org-at-item-p)
  6093. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6094. (org-show-entry)
  6095. (org-with-limited-levels (org-show-children))
  6096. ;; FIXME: This slows down the func way too much.
  6097. ;; How keep drawers hidden in subtree anyway?
  6098. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6099. ;; (org-cycle-hide-drawers 'subtree))
  6100. ;; Fold every list in subtree to top-level items.
  6101. (when (eq org-cycle-include-plain-lists 'integrate)
  6102. (save-excursion
  6103. (org-back-to-heading)
  6104. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6105. (beginning-of-line 1)
  6106. (let* ((struct (org-list-struct))
  6107. (prevs (org-list-prevs-alist struct))
  6108. (end (org-list-get-bottom-point struct)))
  6109. (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
  6110. (org-list-get-all-items (point) struct prevs))
  6111. (goto-char (if (< end eos) end eos)))))))
  6112. (org-unlogged-message "CHILDREN")
  6113. (save-excursion
  6114. (goto-char eos)
  6115. (outline-next-heading)
  6116. (when (outline-invisible-p) (org-flag-heading nil)))
  6117. (setq org-cycle-subtree-status 'children)
  6118. (unless (org-before-first-heading-p)
  6119. (run-hook-with-args 'org-cycle-hook 'children)))
  6120. ((or children-skipped
  6121. (and (eq last-command this-command)
  6122. (eq org-cycle-subtree-status 'children)))
  6123. ;; We just showed the children, or no children are there,
  6124. ;; now show everything.
  6125. (unless (org-before-first-heading-p)
  6126. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6127. (outline-flag-region eoh eos nil)
  6128. (org-unlogged-message
  6129. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6130. (setq org-cycle-subtree-status 'subtree)
  6131. (unless (org-before-first-heading-p)
  6132. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6133. (t
  6134. ;; Default action: hide the subtree.
  6135. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6136. (outline-flag-region eoh eos t)
  6137. (org-unlogged-message "FOLDED")
  6138. (setq org-cycle-subtree-status 'folded)
  6139. (unless (org-before-first-heading-p)
  6140. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6141. ;;;###autoload
  6142. (defun org-global-cycle (&optional arg)
  6143. "Cycle the global visibility. For details see `org-cycle'.
  6144. With \\[universal-argument] prefix arg, switch to startup visibility.
  6145. With a numeric prefix, show all headlines up to that level."
  6146. (interactive "P")
  6147. (let ((org-cycle-include-plain-lists
  6148. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6149. (cond
  6150. ((integerp arg)
  6151. (outline-show-all)
  6152. (outline-hide-sublevels arg)
  6153. (setq org-cycle-global-status 'contents))
  6154. ((equal arg '(4))
  6155. (org-set-startup-visibility)
  6156. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6157. (t
  6158. (org-cycle '(4))))))
  6159. (defun org-set-startup-visibility ()
  6160. "Set the visibility required by startup options and properties."
  6161. (cond
  6162. ((eq org-startup-folded t)
  6163. (org-overview))
  6164. ((eq org-startup-folded 'content)
  6165. (org-content))
  6166. ((or (eq org-startup-folded 'showeverything)
  6167. (eq org-startup-folded nil))
  6168. (outline-show-all)))
  6169. (unless (eq org-startup-folded 'showeverything)
  6170. (when org-hide-block-startup (org-hide-block-all))
  6171. (org-set-visibility-according-to-property 'no-cleanup)
  6172. (org-cycle-hide-archived-subtrees 'all)
  6173. (org-cycle-hide-drawers 'all)
  6174. (org-cycle-show-empty-lines t)))
  6175. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6176. "Switch subtree visibilities according to :VISIBILITY: property."
  6177. (interactive)
  6178. (let (org-show-entry-below)
  6179. (org-with-wide-buffer
  6180. (goto-char (point-min))
  6181. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6182. (if (not (org-at-property-p)) (outline-next-heading)
  6183. (let ((state (match-string 3)))
  6184. (save-excursion
  6185. (org-back-to-heading t)
  6186. (outline-hide-subtree)
  6187. (org-reveal)
  6188. (cond
  6189. ((equal state "folded")
  6190. (outline-hide-subtree))
  6191. ((equal state "children")
  6192. (org-show-hidden-entry)
  6193. (org-show-children))
  6194. ((equal state "content")
  6195. (save-excursion
  6196. (save-restriction
  6197. (org-narrow-to-subtree)
  6198. (org-content))))
  6199. ((member state '("all" "showall"))
  6200. (outline-show-subtree)))))))
  6201. (unless no-cleanup
  6202. (org-cycle-hide-archived-subtrees 'all)
  6203. (org-cycle-hide-drawers 'all)
  6204. (org-cycle-show-empty-lines 'all)))))
  6205. ;; This function uses outline-regexp instead of the more fundamental
  6206. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6207. ;; buffers, where outline-regexp is needed.
  6208. (defun org-overview ()
  6209. "Switch to overview mode, showing only top-level headlines.
  6210. This shows all headlines with a level equal or greater than the level
  6211. of the first headline in the buffer. This is important, because if the
  6212. first headline is not level one, then (hide-sublevels 1) gives confusing
  6213. results."
  6214. (interactive)
  6215. (save-excursion
  6216. (let ((level
  6217. (save-excursion
  6218. (goto-char (point-min))
  6219. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6220. (goto-char (match-beginning 0))
  6221. (funcall outline-level)))))
  6222. (and level (outline-hide-sublevels level)))))
  6223. (defun org-content (&optional arg)
  6224. "Show all headlines in the buffer, like a table of contents.
  6225. With numerical argument N, show content up to level N."
  6226. (interactive "P")
  6227. (org-overview)
  6228. (save-excursion
  6229. ;; Visit all headings and show their offspring
  6230. (and (integerp arg) (org-overview))
  6231. (goto-char (point-max))
  6232. (catch 'exit
  6233. (while (and (progn (condition-case nil
  6234. (outline-previous-visible-heading 1)
  6235. (error (goto-char (point-min))))
  6236. t)
  6237. (looking-at org-outline-regexp))
  6238. (if (integerp arg)
  6239. (org-show-children (1- arg))
  6240. (outline-show-branches))
  6241. (when (bobp) (throw 'exit nil))))))
  6242. (defun org-optimize-window-after-visibility-change (state)
  6243. "Adjust the window after a change in outline visibility.
  6244. This function is the default value of the hook `org-cycle-hook'."
  6245. (when (get-buffer-window (current-buffer))
  6246. (cond
  6247. ((eq state 'content) nil)
  6248. ((eq state 'all) nil)
  6249. ((eq state 'folded) nil)
  6250. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6251. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6252. (defun org-remove-empty-overlays-at (pos)
  6253. "Remove outline overlays that do not contain non-white stuff."
  6254. (mapc
  6255. (lambda (o)
  6256. (and (eq 'outline (overlay-get o 'invisible))
  6257. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6258. (overlay-end o))))
  6259. (delete-overlay o)))
  6260. (overlays-at pos)))
  6261. (defun org-clean-visibility-after-subtree-move ()
  6262. "Fix visibility issues after moving a subtree."
  6263. ;; First, find a reasonable region to look at:
  6264. ;; Start two siblings above, end three below
  6265. (let* ((beg (save-excursion
  6266. (and (org-get-last-sibling)
  6267. (org-get-last-sibling))
  6268. (point)))
  6269. (end (save-excursion
  6270. (and (org-get-next-sibling)
  6271. (org-get-next-sibling)
  6272. (org-get-next-sibling))
  6273. (if (org-at-heading-p)
  6274. (point-at-eol)
  6275. (point))))
  6276. (level (looking-at "\\*+"))
  6277. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6278. (save-excursion
  6279. (save-restriction
  6280. (narrow-to-region beg end)
  6281. (when re
  6282. ;; Properly fold already folded siblings
  6283. (goto-char (point-min))
  6284. (while (re-search-forward re nil t)
  6285. (when (and (not (outline-invisible-p))
  6286. (save-excursion
  6287. (goto-char (point-at-eol)) (outline-invisible-p)))
  6288. (outline-hide-entry))))
  6289. (org-cycle-show-empty-lines 'overview)
  6290. (org-cycle-hide-drawers 'overview)))))
  6291. (defun org-cycle-show-empty-lines (state)
  6292. "Show empty lines above all visible headlines.
  6293. The region to be covered depends on STATE when called through
  6294. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6295. entire buffer covered. Note that an empty line is only shown if there
  6296. are at least `org-cycle-separator-lines' empty lines before the headline."
  6297. (when (/= org-cycle-separator-lines 0)
  6298. (save-excursion
  6299. (let* ((n (abs org-cycle-separator-lines))
  6300. (re (cond
  6301. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6302. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6303. (t (let ((ns (number-to-string (- n 2))))
  6304. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6305. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6306. beg end)
  6307. (cond
  6308. ((memq state '(overview contents t))
  6309. (setq beg (point-min) end (point-max)))
  6310. ((memq state '(children folded))
  6311. (setq beg (point)
  6312. end (progn (org-end-of-subtree t t)
  6313. (line-beginning-position 2)))))
  6314. (when beg
  6315. (goto-char beg)
  6316. (while (re-search-forward re end t)
  6317. (unless (get-char-property (match-end 1) 'invisible)
  6318. (let ((e (match-end 1))
  6319. (b (if (>= org-cycle-separator-lines 0)
  6320. (match-beginning 1)
  6321. (save-excursion
  6322. (goto-char (match-beginning 0))
  6323. (skip-chars-backward " \t\n")
  6324. (line-end-position)))))
  6325. (outline-flag-region b e nil))))))))
  6326. ;; Never hide empty lines at the end of the file.
  6327. (save-excursion
  6328. (goto-char (point-max))
  6329. (outline-previous-heading)
  6330. (outline-end-of-heading)
  6331. (when (and (looking-at "[ \t\n]+")
  6332. (= (match-end 0) (point-max)))
  6333. (outline-flag-region (point) (match-end 0) nil))))
  6334. (defun org-show-empty-lines-in-parent ()
  6335. "Move to the parent and re-show empty lines before visible headlines."
  6336. (save-excursion
  6337. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6338. (org-cycle-show-empty-lines context))))
  6339. (defun org-files-list ()
  6340. "Return `org-agenda-files' list, plus all open org-mode files.
  6341. This is useful for operations that need to scan all of a user's
  6342. open and agenda-wise Org files."
  6343. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6344. (dolist (buf (buffer-list))
  6345. (with-current-buffer buf
  6346. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6347. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6348. files))
  6349. (defsubst org-entry-beginning-position ()
  6350. "Return the beginning position of the current entry."
  6351. (save-excursion (outline-back-to-heading t) (point)))
  6352. (defsubst org-entry-end-position ()
  6353. "Return the end position of the current entry."
  6354. (save-excursion (outline-next-heading) (point)))
  6355. (defun org-cycle-hide-drawers (state &optional exceptions)
  6356. "Re-hide all drawers after a visibility state change.
  6357. When non-nil, optional argument EXCEPTIONS is a list of strings
  6358. specifying which drawers should not be hidden."
  6359. (when (and (derived-mode-p 'org-mode)
  6360. (not (memq state '(overview folded contents))))
  6361. (save-excursion
  6362. (let* ((globalp (memq state '(contents all)))
  6363. (beg (if globalp (point-min) (point)))
  6364. (end (if globalp (point-max)
  6365. (if (eq state 'children)
  6366. (save-excursion (outline-next-heading) (point))
  6367. (org-end-of-subtree t)))))
  6368. (goto-char beg)
  6369. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6370. (unless (member-ignore-case (match-string 1) exceptions)
  6371. (let ((drawer (org-element-at-point)))
  6372. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6373. (org-flag-drawer t drawer)
  6374. ;; Make sure to skip drawer entirely or we might flag
  6375. ;; it another time when matching its ending line with
  6376. ;; `org-drawer-regexp'.
  6377. (goto-char (org-element-property :end drawer))))))))))
  6378. (defun org-flag-drawer (flag &optional element)
  6379. "When FLAG is non-nil, hide the drawer we are at.
  6380. Otherwise make it visible. When optional argument ELEMENT is
  6381. a parsed drawer, as returned by `org-element-at-point', hide or
  6382. show that drawer instead."
  6383. (when (save-excursion
  6384. (beginning-of-line)
  6385. (org-looking-at-p org-drawer-regexp))
  6386. (let ((drawer (or element (org-element-at-point))))
  6387. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6388. (let ((post (org-element-property :post-affiliated drawer)))
  6389. (save-excursion
  6390. (outline-flag-region
  6391. (progn (goto-char post) (line-end-position))
  6392. (progn (goto-char (org-element-property :end drawer))
  6393. (skip-chars-backward " \r\t\n")
  6394. (line-end-position))
  6395. flag))
  6396. ;; When the drawer is hidden away, make sure point lies in
  6397. ;; a visible part of the buffer.
  6398. (when (and flag (> (line-beginning-position) post))
  6399. (goto-char post)))))))
  6400. (defun org-subtree-end-visible-p ()
  6401. "Is the end of the current subtree visible?"
  6402. (pos-visible-in-window-p
  6403. (save-excursion (org-end-of-subtree t) (point))))
  6404. (defun org-first-headline-recenter ()
  6405. "Move cursor to the first headline and recenter the headline."
  6406. (goto-char (point-min))
  6407. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6408. (set-window-start (selected-window) (point-at-bol))))
  6409. ;;; Saving and restoring visibility
  6410. (defun org-outline-overlay-data (&optional use-markers)
  6411. "Return a list of the locations of all outline overlays.
  6412. These are overlays with the `invisible' property value `outline'.
  6413. The return value is a list of cons cells, with start and stop
  6414. positions for each overlay.
  6415. If USE-MARKERS is set, return the positions as markers."
  6416. (let (beg end)
  6417. (save-excursion
  6418. (save-restriction
  6419. (widen)
  6420. (delq nil
  6421. (mapcar (lambda (o)
  6422. (when (eq (overlay-get o 'invisible) 'outline)
  6423. (setq beg (overlay-start o)
  6424. end (overlay-end o))
  6425. (and beg end (> end beg)
  6426. (if use-markers
  6427. (cons (copy-marker beg)
  6428. (copy-marker end t))
  6429. (cons beg end)))))
  6430. (overlays-in (point-min) (point-max))))))))
  6431. (defun org-set-outline-overlay-data (data)
  6432. "Create visibility overlays for all positions in DATA.
  6433. DATA should have been made by `org-outline-overlay-data'."
  6434. (let (o)
  6435. (save-excursion
  6436. (save-restriction
  6437. (widen)
  6438. (outline-show-all)
  6439. (mapc (lambda (c)
  6440. (outline-flag-region (car c) (cdr c) t))
  6441. data)))))
  6442. ;;; Folding of blocks
  6443. (defvar-local org-hide-block-overlays nil
  6444. "Overlays hiding blocks.")
  6445. (defun org-block-map (function &optional start end)
  6446. "Call FUNCTION at the head of all source blocks in the current buffer.
  6447. Optional arguments START and END can be used to limit the range."
  6448. (let ((start (or start (point-min)))
  6449. (end (or end (point-max))))
  6450. (save-excursion
  6451. (goto-char start)
  6452. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6453. (save-excursion
  6454. (save-match-data
  6455. (goto-char (match-beginning 0))
  6456. (funcall function)))))))
  6457. (defun org-hide-block-toggle-all ()
  6458. "Toggle the visibility of all blocks in the current buffer."
  6459. (org-block-map 'org-hide-block-toggle))
  6460. (defun org-hide-block-all ()
  6461. "Fold all blocks in the current buffer."
  6462. (interactive)
  6463. (org-show-block-all)
  6464. (org-block-map 'org-hide-block-toggle-maybe))
  6465. (defun org-show-block-all ()
  6466. "Unfold all blocks in the current buffer."
  6467. (interactive)
  6468. (mapc 'delete-overlay org-hide-block-overlays)
  6469. (setq org-hide-block-overlays nil))
  6470. (defun org-hide-block-toggle-maybe ()
  6471. "Toggle visibility of block at point.
  6472. Unlike to `org-hide-block-toggle', this function does not throw
  6473. an error. Return a non-nil value when toggling is successful."
  6474. (interactive)
  6475. (ignore-errors (org-hide-block-toggle)))
  6476. (defun org-hide-block-toggle (&optional force)
  6477. "Toggle the visibility of the current block.
  6478. When optional argument FORCE is `off', make block visible. If it
  6479. is non-nil, hide it unconditionally. Throw an error when not at
  6480. a block. Return a non-nil value when toggling is successful."
  6481. (interactive)
  6482. (let ((element (org-element-at-point)))
  6483. (unless (memq (org-element-type element)
  6484. '(center-block comment-block dynamic-block example-block
  6485. export-block quote-block special-block
  6486. src-block verse-block))
  6487. (user-error "Not at a block"))
  6488. (let* ((start (save-excursion
  6489. (goto-char (org-element-property :post-affiliated element))
  6490. (line-end-position)))
  6491. (end (save-excursion
  6492. (goto-char (org-element-property :end element))
  6493. (skip-chars-backward " \r\t\n")
  6494. (line-end-position)))
  6495. (overlays (overlays-at start)))
  6496. (cond
  6497. ;; Do nothing when not before or at the block opening line or
  6498. ;; at the block closing line.
  6499. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6500. ((and (not (eq force 'off))
  6501. (not (memq t (mapcar
  6502. (lambda (o)
  6503. (eq (overlay-get o 'invisible) 'org-hide-block))
  6504. overlays))))
  6505. (let ((ov (make-overlay start end)))
  6506. (overlay-put ov 'invisible 'org-hide-block)
  6507. ;; Make the block accessible to `isearch'.
  6508. (overlay-put
  6509. ov 'isearch-open-invisible
  6510. (lambda (ov)
  6511. (when (memq ov org-hide-block-overlays)
  6512. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6513. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6514. (delete-overlay ov))))
  6515. (push ov org-hide-block-overlays)
  6516. ;; When the block is hidden away, make sure point is left in
  6517. ;; a visible part of the buffer.
  6518. (when (> (line-beginning-position) start)
  6519. (goto-char start)
  6520. (beginning-of-line))
  6521. ;; Signal successful toggling.
  6522. t))
  6523. ((or (not force) (eq force 'off))
  6524. (dolist (ov overlays t)
  6525. (when (memq ov org-hide-block-overlays)
  6526. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6527. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6528. (delete-overlay ov))))))))
  6529. ;; org-tab-after-check-for-cycling-hook
  6530. (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
  6531. ;; Remove overlays when changing major mode
  6532. (add-hook 'org-mode-hook
  6533. (lambda () (org-add-hook 'change-major-mode-hook
  6534. 'org-show-block-all 'append 'local)))
  6535. ;;; Org-goto
  6536. (defvar org-goto-window-configuration nil)
  6537. (defvar org-goto-marker nil)
  6538. (defvar org-goto-map)
  6539. (defun org-goto-map ()
  6540. "Set the keymap `org-goto'."
  6541. (setq org-goto-map
  6542. (let ((map (make-sparse-keymap)))
  6543. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6544. mouse-drag-region universal-argument org-occur)))
  6545. (dolist (cmd cmds)
  6546. (substitute-key-definition cmd cmd map global-map)))
  6547. (suppress-keymap map)
  6548. (org-defkey map "\C-m" 'org-goto-ret)
  6549. (org-defkey map [(return)] 'org-goto-ret)
  6550. (org-defkey map [(left)] 'org-goto-left)
  6551. (org-defkey map [(right)] 'org-goto-right)
  6552. (org-defkey map [(control ?g)] 'org-goto-quit)
  6553. (org-defkey map "\C-i" 'org-cycle)
  6554. (org-defkey map [(tab)] 'org-cycle)
  6555. (org-defkey map [(down)] 'outline-next-visible-heading)
  6556. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6557. (if org-goto-auto-isearch
  6558. (if (fboundp 'define-key-after)
  6559. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6560. nil)
  6561. (org-defkey map "q" 'org-goto-quit)
  6562. (org-defkey map "n" 'outline-next-visible-heading)
  6563. (org-defkey map "p" 'outline-previous-visible-heading)
  6564. (org-defkey map "f" 'outline-forward-same-level)
  6565. (org-defkey map "b" 'outline-backward-same-level)
  6566. (org-defkey map "u" 'outline-up-heading))
  6567. (org-defkey map "/" 'org-occur)
  6568. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6569. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6570. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6571. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6572. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6573. map)))
  6574. (defconst org-goto-help
  6575. "Browse buffer copy, to find location or copy text.%s
  6576. RET=jump to location C-g=quit and return to previous location
  6577. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6578. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6579. (defun org-goto (&optional alternative-interface)
  6580. "Look up a different location in the current file, keeping current visibility.
  6581. When you want look-up or go to a different location in a
  6582. document, the fastest way is often to fold the entire buffer and
  6583. then dive into the tree. This method has the disadvantage, that
  6584. the previous location will be folded, which may not be what you
  6585. want.
  6586. This command works around this by showing a copy of the current
  6587. buffer in an indirect buffer, in overview mode. You can dive
  6588. into the tree in that copy, use org-occur and incremental search
  6589. to find a location. When pressing RET or `Q', the command
  6590. returns to the original buffer in which the visibility is still
  6591. unchanged. After RET it will also jump to the location selected
  6592. in the indirect buffer and expose the headline hierarchy above.
  6593. With a prefix argument, use the alternative interface: e.g. if
  6594. `org-goto-interface' is 'outline use 'outline-path-completion."
  6595. (interactive "P")
  6596. (org-goto-map)
  6597. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6598. (org-refile-use-outline-path t)
  6599. (org-refile-target-verify-function nil)
  6600. (interface
  6601. (if (not alternative-interface)
  6602. org-goto-interface
  6603. (if (eq org-goto-interface 'outline)
  6604. 'outline-path-completion
  6605. 'outline)))
  6606. (org-goto-start-pos (point))
  6607. (selected-point
  6608. (if (eq interface 'outline)
  6609. (car (org-get-location (current-buffer) org-goto-help))
  6610. (let ((pa (org-refile-get-location "Goto" nil nil t)))
  6611. (org-refile-check-position pa)
  6612. (nth 3 pa)))))
  6613. (if selected-point
  6614. (progn
  6615. (org-mark-ring-push org-goto-start-pos)
  6616. (goto-char selected-point)
  6617. (when (or (outline-invisible-p) (org-invisible-p2))
  6618. (org-show-context 'org-goto)))
  6619. (message "Quit"))))
  6620. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6621. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6622. (defvar org-goto-local-auto-isearch-map) ; defined below
  6623. (defun org-get-location (buf help)
  6624. "Let the user select a location in the Org-mode buffer BUF.
  6625. This function uses a recursive edit. It returns the selected position
  6626. or nil."
  6627. (org-no-popups
  6628. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6629. (isearch-hide-immediately nil)
  6630. (isearch-search-fun-function
  6631. (lambda () 'org-goto-local-search-headings))
  6632. (org-goto-selected-point org-goto-exit-command))
  6633. (save-excursion
  6634. (save-window-excursion
  6635. (delete-other-windows)
  6636. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6637. (org-pop-to-buffer-same-window
  6638. (condition-case nil
  6639. (make-indirect-buffer (current-buffer) "*org-goto*")
  6640. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6641. (with-output-to-temp-buffer "*Org Help*"
  6642. (princ (format help (if org-goto-auto-isearch
  6643. " Just type for auto-isearch."
  6644. " n/p/f/b/u to navigate, q to quit."))))
  6645. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6646. (setq buffer-read-only nil)
  6647. (let ((org-startup-truncated t)
  6648. (org-startup-folded nil)
  6649. (org-startup-align-all-tables nil))
  6650. (org-mode)
  6651. (org-overview))
  6652. (setq buffer-read-only t)
  6653. (if (and (boundp 'org-goto-start-pos)
  6654. (integer-or-marker-p org-goto-start-pos))
  6655. (progn (goto-char org-goto-start-pos)
  6656. (when (outline-invisible-p)
  6657. (org-show-set-visibility 'lineage)))
  6658. (goto-char (point-min)))
  6659. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6660. (message "Select location and press RET")
  6661. (use-local-map org-goto-map)
  6662. (recursive-edit)))
  6663. (kill-buffer "*org-goto*")
  6664. (cons org-goto-selected-point org-goto-exit-command))))
  6665. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6666. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6667. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6668. (if (fboundp 'isearch-other-control-char)
  6669. (progn
  6670. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6671. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6672. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6673. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6674. (define-key org-goto-local-auto-isearch-map [return] nil))
  6675. (defun org-goto-local-search-headings (string bound noerror)
  6676. "Search and make sure that any matches are in headlines."
  6677. (catch 'return
  6678. (while (if isearch-forward
  6679. (search-forward string bound noerror)
  6680. (search-backward string bound noerror))
  6681. (when (save-match-data
  6682. (and (save-excursion
  6683. (beginning-of-line)
  6684. (looking-at org-complex-heading-regexp))
  6685. (or (not (match-beginning 5))
  6686. (< (point) (match-beginning 5)))))
  6687. (throw 'return (point))))))
  6688. (defun org-goto-local-auto-isearch ()
  6689. "Start isearch."
  6690. (interactive)
  6691. (goto-char (point-min))
  6692. (let ((keys (this-command-keys)))
  6693. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6694. (isearch-mode t)
  6695. (isearch-process-search-char (string-to-char keys)))))
  6696. (defun org-goto-ret (&optional arg)
  6697. "Finish `org-goto' by going to the new location."
  6698. (interactive "P")
  6699. (setq org-goto-selected-point (point)
  6700. org-goto-exit-command 'return)
  6701. (throw 'exit nil))
  6702. (defun org-goto-left ()
  6703. "Finish `org-goto' by going to the new location."
  6704. (interactive)
  6705. (if (org-at-heading-p)
  6706. (progn
  6707. (beginning-of-line 1)
  6708. (setq org-goto-selected-point (point)
  6709. org-goto-exit-command 'left)
  6710. (throw 'exit nil))
  6711. (user-error "Not on a heading")))
  6712. (defun org-goto-right ()
  6713. "Finish `org-goto' by going to the new location."
  6714. (interactive)
  6715. (if (org-at-heading-p)
  6716. (progn
  6717. (setq org-goto-selected-point (point)
  6718. org-goto-exit-command 'right)
  6719. (throw 'exit nil))
  6720. (user-error "Not on a heading")))
  6721. (defun org-goto-quit ()
  6722. "Finish `org-goto' without cursor motion."
  6723. (interactive)
  6724. (setq org-goto-selected-point nil)
  6725. (setq org-goto-exit-command 'quit)
  6726. (throw 'exit nil))
  6727. ;;; Indirect buffer display of subtrees
  6728. (defvar org-indirect-dedicated-frame nil
  6729. "This is the frame being used for indirect tree display.")
  6730. (defvar org-last-indirect-buffer nil)
  6731. (defun org-tree-to-indirect-buffer (&optional arg)
  6732. "Create indirect buffer and narrow it to current subtree.
  6733. With a numerical prefix ARG, go up to this level and then take that tree.
  6734. If ARG is negative, go up that many levels.
  6735. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6736. indirect buffer previously made with this command, to avoid proliferation of
  6737. indirect buffers. However, when you call the command with a \
  6738. \\[universal-argument] prefix, or
  6739. when `org-indirect-buffer-display' is `new-frame', the last buffer
  6740. is kept so that you can work with several indirect buffers at the same time.
  6741. If `org-indirect-buffer-display' is `dedicated-frame', the \
  6742. \\[universal-argument] prefix also
  6743. requests that a new frame be made for the new buffer, so that the dedicated
  6744. frame is not changed."
  6745. (interactive "P")
  6746. (let ((cbuf (current-buffer))
  6747. (cwin (selected-window))
  6748. (pos (point))
  6749. beg end level heading ibuf)
  6750. (save-excursion
  6751. (org-back-to-heading t)
  6752. (when (numberp arg)
  6753. (setq level (org-outline-level))
  6754. (when (< arg 0) (setq arg (+ level arg)))
  6755. (while (> (setq level (org-outline-level)) arg)
  6756. (org-up-heading-safe)))
  6757. (setq beg (point)
  6758. heading (org-get-heading))
  6759. (org-end-of-subtree t t)
  6760. (when (org-at-heading-p) (backward-char 1))
  6761. (setq end (point)))
  6762. (when (and (buffer-live-p org-last-indirect-buffer)
  6763. (not (eq org-indirect-buffer-display 'new-frame))
  6764. (not arg))
  6765. (kill-buffer org-last-indirect-buffer))
  6766. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6767. org-last-indirect-buffer ibuf)
  6768. (cond
  6769. ((or (eq org-indirect-buffer-display 'new-frame)
  6770. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6771. (select-frame (make-frame))
  6772. (delete-other-windows)
  6773. (org-pop-to-buffer-same-window ibuf)
  6774. (org-set-frame-title heading))
  6775. ((eq org-indirect-buffer-display 'dedicated-frame)
  6776. (raise-frame
  6777. (select-frame (or (and org-indirect-dedicated-frame
  6778. (frame-live-p org-indirect-dedicated-frame)
  6779. org-indirect-dedicated-frame)
  6780. (setq org-indirect-dedicated-frame (make-frame)))))
  6781. (delete-other-windows)
  6782. (org-pop-to-buffer-same-window ibuf)
  6783. (org-set-frame-title (concat "Indirect: " heading)))
  6784. ((eq org-indirect-buffer-display 'current-window)
  6785. (org-pop-to-buffer-same-window ibuf))
  6786. ((eq org-indirect-buffer-display 'other-window)
  6787. (pop-to-buffer ibuf))
  6788. (t (error "Invalid value")))
  6789. (when (featurep 'xemacs)
  6790. (save-excursion (org-mode) (turn-on-font-lock)))
  6791. (narrow-to-region beg end)
  6792. (outline-show-all)
  6793. (goto-char pos)
  6794. (run-hook-with-args 'org-cycle-hook 'all)
  6795. (and (window-live-p cwin) (select-window cwin))))
  6796. (defun org-get-indirect-buffer (&optional buffer heading)
  6797. (setq buffer (or buffer (current-buffer)))
  6798. (let ((n 1) (base (buffer-name buffer)) bname)
  6799. (while (buffer-live-p
  6800. (get-buffer
  6801. (setq bname
  6802. (concat base "-"
  6803. (if heading (concat heading "-" (number-to-string n))
  6804. (number-to-string n))))))
  6805. (setq n (1+ n)))
  6806. (condition-case nil
  6807. (make-indirect-buffer buffer bname 'clone)
  6808. (error (make-indirect-buffer buffer bname)))))
  6809. (defun org-set-frame-title (title)
  6810. "Set the title of the current frame to the string TITLE."
  6811. ;; FIXME: how to name a single frame in XEmacs???
  6812. (unless (featurep 'xemacs)
  6813. (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
  6814. ;;;; Structure editing
  6815. ;;; Inserting headlines
  6816. (defun org--line-empty-p (n)
  6817. "Is the Nth next line empty?
  6818. Counts the current line as N = 1 and the previous line as N = 0;
  6819. see `beginning-of-line'."
  6820. (save-excursion
  6821. (and (not (bobp))
  6822. (or (beginning-of-line n) t)
  6823. (save-match-data
  6824. (looking-at "[ \t]*$")))))
  6825. (defun org-previous-line-empty-p ()
  6826. "Is the previous line a blank line?
  6827. When NEXT is non-nil, check the next line instead."
  6828. (org--line-empty-p 0))
  6829. (defun org-next-line-empty-p ()
  6830. "Is the previous line a blank line?
  6831. When NEXT is non-nil, check the next line instead."
  6832. (org--line-empty-p 2))
  6833. (defun org-insert-heading (&optional arg invisible-ok top-level)
  6834. "Insert a new heading or an item with the same depth at point.
  6835. If point is at the beginning of a heading or a list item, insert
  6836. a new heading or a new item above the current one. If point is
  6837. at the beginning of a normal line, turn the line into a heading.
  6838. If point is in the middle of a headline or a list item, split the
  6839. headline or the item and create a new headline/item with the text
  6840. in the current line after point \(see `org-M-RET-may-split-line'
  6841. on how to modify this behavior).
  6842. With one universal prefix argument, set the user option
  6843. `org-insert-heading-respect-content' to t for the duration of
  6844. the command. This modifies the behavior described above in this
  6845. ways: on list items and at the beginning of normal lines, force
  6846. the insertion of a heading after the current subtree.
  6847. With two universal prefix arguments, insert the heading at the
  6848. end of the grandparent subtree. For example, if point is within
  6849. a 2nd-level heading, then it will insert a 2nd-level heading at
  6850. the end of the 1st-level parent heading.
  6851. If point is at the beginning of a headline, insert a sibling
  6852. before the current headline. If point is not at the beginning,
  6853. split the line and create a new headline with the text in the
  6854. current line after point \(see `org-M-RET-may-split-line' on how
  6855. to modify this behavior).
  6856. If point is at the beginning of a normal line, turn this line
  6857. into a heading.
  6858. When INVISIBLE-OK is set, stop at invisible headlines when going
  6859. back. This is important for non-interactive uses of the
  6860. command.
  6861. When optional argument TOP-LEVEL is non-nil, insert a level 1
  6862. heading, unconditionally."
  6863. (interactive "P")
  6864. (when (org-called-interactively-p 'any) (org-reveal))
  6865. (let ((itemp (and (not top-level) (org-in-item-p)))
  6866. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  6867. (respect-content (or org-insert-heading-respect-content
  6868. (equal arg '(4))))
  6869. (initial-content ""))
  6870. (cond
  6871. ((or (= (buffer-size) 0)
  6872. (and (not (save-excursion
  6873. (and (ignore-errors (org-back-to-heading invisible-ok))
  6874. (org-at-heading-p))))
  6875. (or arg (not itemp))))
  6876. ;; At beginning of buffer or so high up that only a heading
  6877. ;; makes sense.
  6878. (cond ((and (bolp) (not respect-content)) (insert "* "))
  6879. ((not respect-content)
  6880. (unless may-split (end-of-line))
  6881. (insert "\n* "))
  6882. ((re-search-forward org-outline-regexp-bol nil t)
  6883. (beginning-of-line)
  6884. (insert "* \n")
  6885. (backward-char))
  6886. (t (goto-char (point-max))
  6887. (insert "\n* ")))
  6888. (run-hooks 'org-insert-heading-hook))
  6889. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  6890. (t
  6891. ;; Maybe move at the end of the subtree
  6892. (when (equal arg '(16))
  6893. (org-up-heading-safe)
  6894. (org-end-of-subtree t))
  6895. ;; Insert a heading
  6896. (save-restriction
  6897. (widen)
  6898. (let* ((level nil)
  6899. (on-heading (org-at-heading-p))
  6900. (empty-line-p (if on-heading
  6901. (org-previous-line-empty-p)
  6902. ;; We will decide later
  6903. nil))
  6904. ;; Get a level string to fall back on.
  6905. (fix-level
  6906. (if (org-before-first-heading-p) "*"
  6907. (save-excursion
  6908. (org-back-to-heading t)
  6909. (when (org-previous-line-empty-p) (setq empty-line-p t))
  6910. (looking-at org-outline-regexp)
  6911. (make-string (1- (length (match-string 0))) ?*))))
  6912. (stars
  6913. (save-excursion
  6914. (condition-case nil
  6915. (if top-level "* "
  6916. (org-back-to-heading invisible-ok)
  6917. (when (and (not on-heading)
  6918. (featurep 'org-inlinetask)
  6919. (integerp org-inlinetask-min-level)
  6920. (>= (length (match-string 0))
  6921. org-inlinetask-min-level))
  6922. ;; Find a heading level before the inline
  6923. ;; task.
  6924. (while (and (setq level (org-up-heading-safe))
  6925. (>= level org-inlinetask-min-level)))
  6926. (if (org-at-heading-p)
  6927. (org-back-to-heading invisible-ok)
  6928. (error "This should not happen")))
  6929. (unless (and (save-excursion
  6930. (save-match-data
  6931. (org-backward-heading-same-level
  6932. 1 invisible-ok))
  6933. (= (point) (match-beginning 0)))
  6934. (not (org-next-line-empty-p)))
  6935. (setq empty-line-p (or empty-line-p
  6936. (org-previous-line-empty-p))))
  6937. (match-string 0))
  6938. (error (or fix-level "* ")))))
  6939. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  6940. (blank (if (eq blank-a 'auto) empty-line-p blank-a))
  6941. pos hide-previous previous-pos)
  6942. ;; If we insert after content, move there and clean up
  6943. ;; whitespace.
  6944. (when (and respect-content
  6945. (not (org-looking-at-p org-outline-regexp-bol)))
  6946. (if (not (org-before-first-heading-p))
  6947. (org-end-of-subtree nil t)
  6948. (re-search-forward org-outline-regexp-bol)
  6949. (beginning-of-line 0))
  6950. (skip-chars-backward " \r\t\n")
  6951. (and (not (org-looking-back "^\\*+" (line-beginning-position)))
  6952. (looking-at "[ \t]+") (replace-match ""))
  6953. (unless (eobp) (forward-char 1))
  6954. (when (looking-at "^\\*")
  6955. (unless (bobp) (backward-char 1))
  6956. (insert "\n")))
  6957. ;; If we are splitting, grab the text that should be moved
  6958. ;; to the new headline.
  6959. (when may-split
  6960. (if (org-at-heading-p)
  6961. ;; This is a heading: split intelligently (keeping
  6962. ;; tags).
  6963. (let ((pos (point)))
  6964. (beginning-of-line)
  6965. (unless (looking-at org-complex-heading-regexp)
  6966. (error "This should not happen"))
  6967. (when (and (match-beginning 4)
  6968. (> pos (match-beginning 4))
  6969. (< pos (match-end 4)))
  6970. (setq initial-content (buffer-substring pos (match-end 4)))
  6971. (goto-char pos)
  6972. (delete-region (point) (match-end 4))
  6973. (if (looking-at "[ \t]*$")
  6974. (replace-match "")
  6975. (insert (make-string (length initial-content) ?\s)))
  6976. (setq initial-content (org-trim initial-content)))
  6977. (goto-char pos))
  6978. ;; A normal line.
  6979. (setq initial-content
  6980. (org-trim
  6981. (delete-and-extract-region (point) (line-end-position))))))
  6982. ;; If we are at the beginning of the line, insert before it.
  6983. ;; Otherwise, after it.
  6984. (cond
  6985. ((and (bolp) (looking-at "[ \t]*$")))
  6986. ((bolp) (save-excursion (insert "\n")))
  6987. (t (end-of-line)
  6988. (insert "\n")))
  6989. ;; Insert the new heading
  6990. (insert stars)
  6991. (just-one-space)
  6992. (insert initial-content)
  6993. (unless (and blank (org-previous-line-empty-p))
  6994. (org-N-empty-lines-before-current (if blank 1 0)))
  6995. ;; Adjust visibility, which may be messed up if we removed
  6996. ;; blank lines while previous entry was hidden.
  6997. (let ((bol (line-beginning-position)))
  6998. (dolist (o (overlays-at (1- bol)))
  6999. (when (and (eq (overlay-get o 'invisible) 'outline)
  7000. (eq (overlay-end o) bol))
  7001. (move-overlay o (overlay-start o) (1- bol)))))
  7002. (run-hooks 'org-insert-heading-hook)))))))
  7003. (defun org-N-empty-lines-before-current (N)
  7004. "Make the number of empty lines before current exactly N.
  7005. So this will delete or add empty lines."
  7006. (save-excursion
  7007. (beginning-of-line)
  7008. (let ((p (point)))
  7009. (skip-chars-backward " \r\t\n")
  7010. (unless (bolp) (forward-line))
  7011. (delete-region (point) p))
  7012. (when (> N 0) (insert (make-string N ?\n)))))
  7013. (defun org-get-heading (&optional no-tags no-todo)
  7014. "Return the heading of the current entry, without the stars.
  7015. When NO-TAGS is non-nil, don't include tags.
  7016. When NO-TODO is non-nil, don't include TODO keywords."
  7017. (save-excursion
  7018. (org-back-to-heading t)
  7019. (cond
  7020. ((and no-tags no-todo)
  7021. (looking-at org-complex-heading-regexp)
  7022. (match-string 4))
  7023. (no-tags
  7024. (looking-at (concat org-outline-regexp
  7025. "\\(.*?\\)"
  7026. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7027. (match-string 1))
  7028. (no-todo
  7029. (looking-at org-todo-line-regexp)
  7030. (match-string 3))
  7031. (t (looking-at org-heading-regexp)
  7032. (match-string 2)))))
  7033. (defvar orgstruct-mode) ; defined below
  7034. (defun org-heading-components ()
  7035. "Return the components of the current heading.
  7036. This is a list with the following elements:
  7037. - the level as an integer
  7038. - the reduced level, different if `org-odd-levels-only' is set.
  7039. - the TODO keyword, or nil
  7040. - the priority character, like ?A, or nil if no priority is given
  7041. - the headline text itself, or the tags string if no headline text
  7042. - the tags string, or nil."
  7043. (save-excursion
  7044. (org-back-to-heading t)
  7045. (when (let (case-fold-search)
  7046. (looking-at
  7047. (if orgstruct-mode
  7048. org-heading-regexp
  7049. org-complex-heading-regexp)))
  7050. (if orgstruct-mode
  7051. (list (length (match-string 1))
  7052. (org-reduced-level (length (match-string 1)))
  7053. nil
  7054. nil
  7055. (match-string 2)
  7056. nil)
  7057. (list (length (match-string 1))
  7058. (org-reduced-level (length (match-string 1)))
  7059. (org-match-string-no-properties 2)
  7060. (and (match-end 3) (aref (match-string 3) 2))
  7061. (org-match-string-no-properties 4)
  7062. (org-match-string-no-properties 5))))))
  7063. (defun org-get-entry ()
  7064. "Get the entry text, after heading, entire subtree."
  7065. (save-excursion
  7066. (org-back-to-heading t)
  7067. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7068. (defun org-insert-heading-after-current ()
  7069. "Insert a new heading with same level as current, after current subtree."
  7070. (interactive)
  7071. (org-back-to-heading)
  7072. (org-insert-heading)
  7073. (org-move-subtree-down)
  7074. (end-of-line 1))
  7075. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7076. "Insert heading with `org-insert-heading-respect-content' set to t."
  7077. (interactive)
  7078. (org-insert-heading '(4) invisible-ok))
  7079. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7080. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7081. (interactive)
  7082. (org-insert-todo-heading force-state '(4)))
  7083. (defun org-insert-todo-heading (arg &optional force-heading)
  7084. "Insert a new heading with the same level and TODO state as current heading.
  7085. If the heading has no TODO state, or if the state is DONE, use the first
  7086. state (TODO by default). Also with one prefix arg, force first state. With
  7087. two prefix args, force inserting at the end of the parent subtree."
  7088. (interactive "P")
  7089. (when (or force-heading (not (org-insert-item 'checkbox)))
  7090. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7091. force-heading))
  7092. (save-excursion
  7093. (org-back-to-heading)
  7094. (outline-previous-heading)
  7095. (looking-at org-todo-line-regexp))
  7096. (let*
  7097. ((new-mark-x
  7098. (if (or (equal arg '(4))
  7099. (not (match-beginning 2))
  7100. (member (match-string 2) org-done-keywords))
  7101. (car org-todo-keywords-1)
  7102. (match-string 2)))
  7103. (new-mark
  7104. (or
  7105. (run-hook-with-args-until-success
  7106. 'org-todo-get-default-hook new-mark-x nil)
  7107. new-mark-x)))
  7108. (beginning-of-line 1)
  7109. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7110. (if org-treat-insert-todo-heading-as-state-change
  7111. (org-todo new-mark)
  7112. (insert new-mark " "))))
  7113. (when org-provide-todo-statistics
  7114. (org-update-parent-todo-statistics))))
  7115. (defun org-insert-subheading (arg)
  7116. "Insert a new subheading and demote it.
  7117. Works for outline headings and for plain lists alike."
  7118. (interactive "P")
  7119. (org-insert-heading arg)
  7120. (cond
  7121. ((org-at-heading-p) (org-do-demote))
  7122. ((org-at-item-p) (org-indent-item))))
  7123. (defun org-insert-todo-subheading (arg)
  7124. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7125. Works for outline headings and for plain lists alike."
  7126. (interactive "P")
  7127. (org-insert-todo-heading arg)
  7128. (cond
  7129. ((org-at-heading-p) (org-do-demote))
  7130. ((org-at-item-p) (org-indent-item))))
  7131. ;;; Promotion and Demotion
  7132. (defvar org-after-demote-entry-hook nil
  7133. "Hook run after an entry has been demoted.
  7134. The cursor will be at the beginning of the entry.
  7135. When a subtree is being demoted, the hook will be called for each node.")
  7136. (defvar org-after-promote-entry-hook nil
  7137. "Hook run after an entry has been promoted.
  7138. The cursor will be at the beginning of the entry.
  7139. When a subtree is being promoted, the hook will be called for each node.")
  7140. (defun org-promote-subtree ()
  7141. "Promote the entire subtree.
  7142. See also `org-promote'."
  7143. (interactive)
  7144. (save-excursion
  7145. (org-with-limited-levels (org-map-tree 'org-promote)))
  7146. (org-fix-position-after-promote))
  7147. (defun org-demote-subtree ()
  7148. "Demote the entire subtree.
  7149. See `org-demote' and `org-promote'."
  7150. (interactive)
  7151. (save-excursion
  7152. (org-with-limited-levels (org-map-tree 'org-demote)))
  7153. (org-fix-position-after-promote))
  7154. (defun org-do-promote ()
  7155. "Promote the current heading higher up the tree.
  7156. If the region is active in `transient-mark-mode', promote all
  7157. headings in the region."
  7158. (interactive)
  7159. (save-excursion
  7160. (if (org-region-active-p)
  7161. (org-map-region 'org-promote (region-beginning) (region-end))
  7162. (org-promote)))
  7163. (org-fix-position-after-promote))
  7164. (defun org-do-demote ()
  7165. "Demote the current heading lower down the tree.
  7166. If the region is active in `transient-mark-mode', demote all
  7167. headings in the region."
  7168. (interactive)
  7169. (save-excursion
  7170. (if (org-region-active-p)
  7171. (org-map-region 'org-demote (region-beginning) (region-end))
  7172. (org-demote)))
  7173. (org-fix-position-after-promote))
  7174. (defun org-fix-position-after-promote ()
  7175. "Fix cursor position and indentation after demoting/promoting."
  7176. (let ((pos (point)))
  7177. (when (save-excursion
  7178. (beginning-of-line 1)
  7179. (looking-at org-todo-line-regexp)
  7180. (or (equal pos (match-end 1)) (equal pos (match-end 2))))
  7181. (cond ((eobp) (insert " "))
  7182. ((eolp) (insert " "))
  7183. ((equal (char-after) ?\ ) (forward-char 1))))))
  7184. (defun org-current-level ()
  7185. "Return the level of the current entry, or nil if before the first headline.
  7186. The level is the number of stars at the beginning of the
  7187. headline. Use `org-reduced-level' to remove the effect of
  7188. `org-odd-levels'. Unlike to `org-outline-level', this function
  7189. ignores inlinetasks."
  7190. (let ((level (org-with-limited-levels (org-outline-level))))
  7191. (and (> level 0) level)))
  7192. (defun org-get-previous-line-level ()
  7193. "Return the outline depth of the last headline before the current line.
  7194. Returns 0 for the first headline in the buffer, and nil if before the
  7195. first headline."
  7196. (and (org-current-level)
  7197. (or (and (/= (line-beginning-position) (point-min))
  7198. (save-excursion (beginning-of-line 0) (org-current-level)))
  7199. 0)))
  7200. (defun org-reduced-level (l)
  7201. "Compute the effective level of a heading.
  7202. This takes into account the setting of `org-odd-levels-only'."
  7203. (cond
  7204. ((zerop l) 0)
  7205. (org-odd-levels-only (1+ (floor (/ l 2))))
  7206. (t l)))
  7207. (defun org-level-increment ()
  7208. "Return the number of stars that will be added or removed at a
  7209. time to headlines when structure editing, based on the value of
  7210. `org-odd-levels-only'."
  7211. (if org-odd-levels-only 2 1))
  7212. (defun org-get-valid-level (level &optional change)
  7213. "Rectify a level change under the influence of `org-odd-levels-only'
  7214. LEVEL is a current level, CHANGE is by how much the level should be
  7215. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7216. even level numbers will become the next higher odd number."
  7217. (if org-odd-levels-only
  7218. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7219. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7220. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7221. (max 1 (+ level (or change 0)))))
  7222. (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
  7223. (defun org-promote ()
  7224. "Promote the current heading higher up the tree."
  7225. (org-with-wide-buffer
  7226. (org-back-to-heading t)
  7227. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7228. after-change-functions))
  7229. (level (save-match-data (funcall outline-level)))
  7230. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7231. (diff (abs (- level (length up-head) -1))))
  7232. (cond
  7233. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7234. (replace-match "# " nil t))
  7235. ((= level 1)
  7236. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7237. (t (replace-match up-head nil t)))
  7238. (unless (= level 1)
  7239. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7240. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7241. (run-hooks 'org-after-promote-entry-hook))))
  7242. (defun org-demote ()
  7243. "Demote the current heading lower down the tree."
  7244. (org-with-wide-buffer
  7245. (org-back-to-heading t)
  7246. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7247. after-change-functions))
  7248. (level (save-match-data (funcall outline-level)))
  7249. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7250. (diff (abs (- level (length down-head) -1))))
  7251. (replace-match down-head nil t)
  7252. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7253. (when org-adapt-indentation (org-fixup-indentation diff))
  7254. (run-hooks 'org-after-demote-entry-hook))))
  7255. (defun org-cycle-level ()
  7256. "Cycle the level of an empty headline through possible states.
  7257. This goes first to child, then to parent, level, then up the hierarchy.
  7258. After top level, it switches back to sibling level."
  7259. (interactive)
  7260. (let ((org-adapt-indentation nil))
  7261. (when (org-point-at-end-of-empty-headline)
  7262. (setq this-command 'org-cycle-level) ; Only needed for caching
  7263. (let ((cur-level (org-current-level))
  7264. (prev-level (org-get-previous-line-level)))
  7265. (cond
  7266. ;; If first headline in file, promote to top-level.
  7267. ((= prev-level 0)
  7268. (loop repeat (/ (- cur-level 1) (org-level-increment))
  7269. do (org-do-promote)))
  7270. ;; If same level as prev, demote one.
  7271. ((= prev-level cur-level)
  7272. (org-do-demote))
  7273. ;; If parent is top-level, promote to top level if not already.
  7274. ((= prev-level 1)
  7275. (loop repeat (/ (- cur-level 1) (org-level-increment))
  7276. do (org-do-promote)))
  7277. ;; If top-level, return to prev-level.
  7278. ((= cur-level 1)
  7279. (loop repeat (/ (- prev-level 1) (org-level-increment))
  7280. do (org-do-demote)))
  7281. ;; If less than prev-level, promote one.
  7282. ((< cur-level prev-level)
  7283. (org-do-promote))
  7284. ;; If deeper than prev-level, promote until higher than
  7285. ;; prev-level.
  7286. ((> cur-level prev-level)
  7287. (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7288. do (org-do-promote))))
  7289. t))))
  7290. (defun org-map-tree (fun)
  7291. "Call FUN for every heading underneath the current one."
  7292. (org-back-to-heading)
  7293. (let ((level (funcall outline-level)))
  7294. (save-excursion
  7295. (funcall fun)
  7296. (while (and (progn
  7297. (outline-next-heading)
  7298. (> (funcall outline-level) level))
  7299. (not (eobp)))
  7300. (funcall fun)))))
  7301. (defun org-map-region (fun beg end)
  7302. "Call FUN for every heading between BEG and END."
  7303. (let ((org-ignore-region t))
  7304. (save-excursion
  7305. (setq end (copy-marker end))
  7306. (goto-char beg)
  7307. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7308. (< (point) end))
  7309. (funcall fun))
  7310. (while (and (progn
  7311. (outline-next-heading)
  7312. (< (point) end))
  7313. (not (eobp)))
  7314. (funcall fun)))))
  7315. (defun org-fixup-indentation (diff)
  7316. "Change the indentation in the current entry by DIFF.
  7317. DIFF is an integer. Indentation is done according to the
  7318. following rules:
  7319. - Planning information and property drawers are always indented
  7320. according to the new level of the headline;
  7321. - Footnote definitions and their contents are ignored;
  7322. - Inlinetasks' boundaries are not shifted;
  7323. - Empty lines are ignored;
  7324. - Other lines' indentation are shifted by DIFF columns, unless
  7325. it would introduce a structural change in the document, in
  7326. which case no shifting is done at all.
  7327. Assume point is at a heading or an inlinetask beginning."
  7328. (org-with-wide-buffer
  7329. (narrow-to-region (line-beginning-position)
  7330. (save-excursion
  7331. (if (org-with-limited-levels (org-at-heading-p))
  7332. (org-with-limited-levels (outline-next-heading))
  7333. (org-inlinetask-goto-end))
  7334. (point)))
  7335. (forward-line)
  7336. ;; Indent properly planning info and property drawer.
  7337. (when (org-looking-at-p org-planning-line-re)
  7338. (org-indent-line)
  7339. (forward-line))
  7340. (when (looking-at org-property-drawer-re)
  7341. (goto-char (match-end 0))
  7342. (forward-line)
  7343. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7344. (catch 'no-shift
  7345. (when (zerop diff) (throw 'no-shift nil))
  7346. ;; If DIFF is negative, first check if a shift is possible at all
  7347. ;; (e.g., it doesn't break structure). This can only happen if
  7348. ;; some contents are not properly indented.
  7349. (let ((case-fold-search t))
  7350. (when (< diff 0)
  7351. (let ((diff (- diff))
  7352. (forbidden-re (concat org-outline-regexp
  7353. "\\|"
  7354. (substring org-footnote-definition-re 1))))
  7355. (save-excursion
  7356. (while (not (eobp))
  7357. (cond
  7358. ((org-looking-at-p "[ \t]*$") (forward-line))
  7359. ((and (org-looking-at-p org-footnote-definition-re)
  7360. (let ((e (org-element-at-point)))
  7361. (and (eq (org-element-type e) 'footnote-definition)
  7362. (goto-char (org-element-property :end e))))))
  7363. ((org-looking-at-p org-outline-regexp) (forward-line))
  7364. ;; Give up if shifting would move before column 0 or
  7365. ;; if it would introduce a headline or a footnote
  7366. ;; definition.
  7367. (t
  7368. (skip-chars-forward " \t")
  7369. (let ((ind (current-column)))
  7370. (when (or (< ind diff)
  7371. (and (= ind diff) (org-looking-at-p forbidden-re)))
  7372. (throw 'no-shift nil)))
  7373. ;; Ignore contents of example blocks and source
  7374. ;; blocks if their indentation is meant to be
  7375. ;; preserved. Jump to block's closing line.
  7376. (beginning-of-line)
  7377. (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7378. (let ((e (org-element-at-point)))
  7379. (and (memq (org-element-type e)
  7380. '(example-block src-block))
  7381. (or org-src-preserve-indentation
  7382. (org-element-property :preserve-indent e))
  7383. (goto-char (org-element-property :end e))
  7384. (progn (skip-chars-backward " \r\t\n")
  7385. (beginning-of-line)
  7386. t))))
  7387. (forward-line))))))))
  7388. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7389. ;; by DIFF. Also skip contents of source or example blocks
  7390. ;; when indentation is meant to be preserved.
  7391. (while (not (eobp))
  7392. (cond
  7393. ((and (org-looking-at-p org-footnote-definition-re)
  7394. (let ((e (org-element-at-point)))
  7395. (and (eq (org-element-type e) 'footnote-definition)
  7396. (goto-char (org-element-property :end e))))))
  7397. ((org-looking-at-p org-outline-regexp) (forward-line))
  7398. ((org-looking-at-p "[ \t]*$") (forward-line))
  7399. (t
  7400. (org-indent-line-to (+ (org-get-indentation) diff))
  7401. (beginning-of-line)
  7402. (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7403. (let ((e (org-element-at-point)))
  7404. (and (memq (org-element-type e)
  7405. '(example-block src-block))
  7406. (or org-src-preserve-indentation
  7407. (org-element-property :preserve-indent e))
  7408. (goto-char (org-element-property :end e))
  7409. (progn (skip-chars-backward " \r\t\n")
  7410. (beginning-of-line)
  7411. t))))
  7412. (forward-line)))))))))
  7413. (defun org-convert-to-odd-levels ()
  7414. "Convert an org-mode file with all levels allowed to one with odd levels.
  7415. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7416. level 5 etc."
  7417. (interactive)
  7418. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7419. (let ((outline-level 'org-outline-level)
  7420. (org-odd-levels-only nil) n)
  7421. (save-excursion
  7422. (goto-char (point-min))
  7423. (while (re-search-forward "^\\*\\*+ " nil t)
  7424. (setq n (- (length (match-string 0)) 2))
  7425. (while (>= (setq n (1- n)) 0)
  7426. (org-demote))
  7427. (end-of-line 1))))))
  7428. (defun org-convert-to-oddeven-levels ()
  7429. "Convert an org-mode file with only odd levels to one with odd/even levels.
  7430. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7431. file contains a section with an even level, conversion would
  7432. destroy the structure of the file. An error is signaled in this
  7433. case."
  7434. (interactive)
  7435. (goto-char (point-min))
  7436. ;; First check if there are no even levels
  7437. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7438. (org-show-set-visibility 'canonical)
  7439. (error "Not all levels are odd in this file. Conversion not possible"))
  7440. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7441. (let ((outline-regexp org-outline-regexp)
  7442. (outline-level 'org-outline-level)
  7443. (org-odd-levels-only nil) n)
  7444. (save-excursion
  7445. (goto-char (point-min))
  7446. (while (re-search-forward "^\\*\\*+ " nil t)
  7447. (setq n (/ (1- (length (match-string 0))) 2))
  7448. (while (>= (setq n (1- n)) 0)
  7449. (org-promote))
  7450. (end-of-line 1))))))
  7451. (defun org-tr-level (n)
  7452. "Make N odd if required."
  7453. (if org-odd-levels-only (1+ (/ n 2)) n))
  7454. ;;; Vertical tree motion, cutting and pasting of subtrees
  7455. (defun org-move-subtree-up (&optional arg)
  7456. "Move the current subtree up past ARG headlines of the same level."
  7457. (interactive "p")
  7458. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7459. (defun org-move-subtree-down (&optional arg)
  7460. "Move the current subtree down past ARG headlines of the same level."
  7461. (interactive "p")
  7462. (setq arg (prefix-numeric-value arg))
  7463. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7464. 'org-get-last-sibling))
  7465. (ins-point (make-marker))
  7466. (cnt (abs arg))
  7467. (col (current-column))
  7468. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7469. ;; Select the tree
  7470. (org-back-to-heading)
  7471. (setq beg0 (point))
  7472. (save-excursion
  7473. (setq ne-beg (org-back-over-empty-lines))
  7474. (setq beg (point)))
  7475. (save-match-data
  7476. (save-excursion (outline-end-of-heading)
  7477. (setq folded (outline-invisible-p)))
  7478. (progn (org-end-of-subtree nil t)
  7479. (unless (eobp) (backward-char))))
  7480. (outline-next-heading)
  7481. (setq ne-end (org-back-over-empty-lines))
  7482. (setq end (point))
  7483. (goto-char beg0)
  7484. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7485. ;; include less whitespace
  7486. (save-excursion
  7487. (goto-char beg)
  7488. (forward-line (- ne-beg ne-end))
  7489. (setq beg (point))))
  7490. ;; Find insertion point, with error handling
  7491. (while (> cnt 0)
  7492. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7493. (progn (goto-char beg0)
  7494. (user-error "Cannot move past superior level or buffer limit")))
  7495. (setq cnt (1- cnt)))
  7496. (when (> arg 0)
  7497. ;; Moving forward - still need to move over subtree
  7498. (org-end-of-subtree t t)
  7499. (save-excursion
  7500. (org-back-over-empty-lines)
  7501. (or (bolp) (newline))))
  7502. (setq ne-ins (org-back-over-empty-lines))
  7503. (move-marker ins-point (point))
  7504. (setq txt (buffer-substring beg end))
  7505. (org-save-markers-in-region beg end)
  7506. (delete-region beg end)
  7507. (org-remove-empty-overlays-at beg)
  7508. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7509. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7510. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7511. (let ((bbb (point)))
  7512. (insert-before-markers txt)
  7513. (org-reinstall-markers-in-region bbb)
  7514. (move-marker ins-point bbb))
  7515. (or (bolp) (insert "\n"))
  7516. (setq ins-end (point))
  7517. (goto-char ins-point)
  7518. (org-skip-whitespace)
  7519. (when (and (< arg 0)
  7520. (org-first-sibling-p)
  7521. (> ne-ins ne-beg))
  7522. ;; Move whitespace back to beginning
  7523. (save-excursion
  7524. (goto-char ins-end)
  7525. (let ((kill-whole-line t))
  7526. (kill-line (- ne-ins ne-beg)) (point)))
  7527. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7528. (move-marker ins-point nil)
  7529. (if folded
  7530. (outline-hide-subtree)
  7531. (org-show-entry)
  7532. (org-show-children)
  7533. (org-cycle-hide-drawers 'children))
  7534. (org-clean-visibility-after-subtree-move)
  7535. ;; move back to the initial column we were at
  7536. (move-to-column col)))
  7537. (defvar org-subtree-clip ""
  7538. "Clipboard for cut and paste of subtrees.
  7539. This is actually only a copy of the kill, because we use the normal kill
  7540. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7541. (defvar org-subtree-clip-folded nil
  7542. "Was the last copied subtree folded?
  7543. This is used to fold the tree back after pasting.")
  7544. (defun org-cut-subtree (&optional n)
  7545. "Cut the current subtree into the clipboard.
  7546. With prefix arg N, cut this many sequential subtrees.
  7547. This is a short-hand for marking the subtree and then cutting it."
  7548. (interactive "p")
  7549. (org-copy-subtree n 'cut))
  7550. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7551. "Copy the current subtree it in the clipboard.
  7552. With prefix arg N, copy this many sequential subtrees.
  7553. This is a short-hand for marking the subtree and then copying it.
  7554. If CUT is non-nil, actually cut the subtree.
  7555. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7556. of some markers in the region, even if CUT is non-nil. This is
  7557. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7558. (interactive "p")
  7559. (let (beg end folded (beg0 (point)))
  7560. (if (org-called-interactively-p 'any)
  7561. (org-back-to-heading nil) ; take what looks like a subtree
  7562. (org-back-to-heading t)) ; take what is really there
  7563. (setq beg (point))
  7564. (skip-chars-forward " \t\r\n")
  7565. (save-match-data
  7566. (if nosubtrees
  7567. (outline-next-heading)
  7568. (save-excursion (outline-end-of-heading)
  7569. (setq folded (outline-invisible-p)))
  7570. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7571. (org-end-of-subtree t t)))
  7572. ;; Include the end of an inlinetask
  7573. (when (and (featurep 'org-inlinetask)
  7574. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7575. "END[ \t]*$")))
  7576. (end-of-line))
  7577. (setq end (point))
  7578. (goto-char beg0)
  7579. (when (> end beg)
  7580. (setq org-subtree-clip-folded folded)
  7581. (when (or cut force-store-markers)
  7582. (org-save-markers-in-region beg end))
  7583. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7584. (setq org-subtree-clip (current-kill 0))
  7585. (message "%s: Subtree(s) with %d characters"
  7586. (if cut "Cut" "Copied")
  7587. (length org-subtree-clip)))))
  7588. (defun org-paste-subtree (&optional level tree for-yank remove)
  7589. "Paste the clipboard as a subtree, with modification of headline level.
  7590. The entire subtree is promoted or demoted in order to match a new headline
  7591. level.
  7592. If the cursor is at the beginning of a headline, the same level as
  7593. that headline is used to paste the tree.
  7594. If not, the new level is derived from the *visible* headings
  7595. before and after the insertion point, and taken to be the inferior headline
  7596. level of the two. So if the previous visible heading is level 3 and the
  7597. next is level 4 (or vice versa), level 4 will be used for insertion.
  7598. This makes sure that the subtree remains an independent subtree and does
  7599. not swallow low level entries.
  7600. You can also force a different level, either by using a numeric prefix
  7601. argument, or by inserting the heading marker by hand. For example, if the
  7602. cursor is after \"*****\", then the tree will be shifted to level 5.
  7603. If optional TREE is given, use this text instead of the kill ring.
  7604. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7605. move back over whitespace before inserting, and move point to the end of
  7606. the inserted text when done.
  7607. When REMOVE is non-nil, remove the subtree from the clipboard."
  7608. (interactive "P")
  7609. (setq tree (or tree (and kill-ring (current-kill 0))))
  7610. (unless (org-kill-is-subtree-p tree)
  7611. (user-error "%s"
  7612. (substitute-command-keys
  7613. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7614. (org-with-limited-levels
  7615. (let* ((visp (not (outline-invisible-p)))
  7616. (txt tree)
  7617. (^re_ "\\(\\*+\\)[ \t]*")
  7618. (old-level (if (string-match org-outline-regexp-bol txt)
  7619. (- (match-end 0) (match-beginning 0) 1)
  7620. -1))
  7621. (force-level (cond (level (prefix-numeric-value level))
  7622. ((and (looking-at "[ \t]*$")
  7623. (string-match
  7624. "^\\*+$" (buffer-substring
  7625. (point-at-bol) (point))))
  7626. (- (match-end 0) (match-beginning 0)))
  7627. ((and (bolp)
  7628. (looking-at org-outline-regexp))
  7629. (- (match-end 0) (point) 1))))
  7630. (previous-level (save-excursion
  7631. (condition-case nil
  7632. (progn
  7633. (outline-previous-visible-heading 1)
  7634. (if (looking-at ^re_)
  7635. (- (match-end 0) (match-beginning 0) 1)
  7636. 1))
  7637. (error 1))))
  7638. (next-level (save-excursion
  7639. (condition-case nil
  7640. (progn
  7641. (or (looking-at org-outline-regexp)
  7642. (outline-next-visible-heading 1))
  7643. (if (looking-at ^re_)
  7644. (- (match-end 0) (match-beginning 0) 1)
  7645. 1))
  7646. (error 1))))
  7647. (new-level (or force-level (max previous-level next-level)))
  7648. (shift (if (or (= old-level -1)
  7649. (= new-level -1)
  7650. (= old-level new-level))
  7651. 0
  7652. (- new-level old-level)))
  7653. (delta (if (> shift 0) -1 1))
  7654. (func (if (> shift 0) 'org-demote 'org-promote))
  7655. (org-odd-levels-only nil)
  7656. beg end newend)
  7657. ;; Remove the forced level indicator
  7658. (when force-level
  7659. (delete-region (point-at-bol) (point)))
  7660. ;; Paste
  7661. (beginning-of-line (if (bolp) 1 2))
  7662. (setq beg (point))
  7663. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7664. (insert-before-markers txt)
  7665. (unless (string-match "\n\\'" txt) (insert "\n"))
  7666. (setq newend (point))
  7667. (org-reinstall-markers-in-region beg)
  7668. (setq end (point))
  7669. (goto-char beg)
  7670. (skip-chars-forward " \t\n\r")
  7671. (setq beg (point))
  7672. (when (and (outline-invisible-p) visp)
  7673. (save-excursion (outline-show-heading)))
  7674. ;; Shift if necessary
  7675. (unless (= shift 0)
  7676. (save-restriction
  7677. (narrow-to-region beg end)
  7678. (while (not (= shift 0))
  7679. (org-map-region func (point-min) (point-max))
  7680. (setq shift (+ delta shift)))
  7681. (goto-char (point-min))
  7682. (setq newend (point-max))))
  7683. (when (or (org-called-interactively-p 'interactive) for-yank)
  7684. (message "Clipboard pasted as level %d subtree" new-level))
  7685. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7686. kill-ring
  7687. (eq org-subtree-clip (current-kill 0))
  7688. org-subtree-clip-folded)
  7689. ;; The tree was folded before it was killed/copied
  7690. (outline-hide-subtree))
  7691. (and for-yank (goto-char newend))
  7692. (and remove (setq kill-ring (cdr kill-ring))))))
  7693. (defun org-kill-is-subtree-p (&optional txt)
  7694. "Check if the current kill is an outline subtree, or a set of trees.
  7695. Returns nil if kill does not start with a headline, or if the first
  7696. headline level is not the largest headline level in the tree.
  7697. So this will actually accept several entries of equal levels as well,
  7698. which is OK for `org-paste-subtree'.
  7699. If optional TXT is given, check this string instead of the current kill."
  7700. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7701. (re (org-get-limited-outline-regexp))
  7702. (^re (concat "^" re))
  7703. (start-level (and kill
  7704. (string-match
  7705. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7706. kill)
  7707. (- (match-end 2) (match-beginning 2) 1)))
  7708. (start (1+ (or (match-beginning 2) -1))))
  7709. (if (not start-level)
  7710. (progn
  7711. nil) ;; does not even start with a heading
  7712. (catch 'exit
  7713. (while (setq start (string-match ^re kill (1+ start)))
  7714. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7715. (throw 'exit nil)))
  7716. t))))
  7717. (defvar org-markers-to-move nil
  7718. "Markers that should be moved with a cut-and-paste operation.
  7719. Those markers are stored together with their positions relative to
  7720. the start of the region.")
  7721. (defun org-save-markers-in-region (beg end)
  7722. "Check markers in region.
  7723. If these markers are between BEG and END, record their position relative
  7724. to BEG, so that after moving the block of text, we can put the markers back
  7725. into place.
  7726. This function gets called just before an entry or tree gets cut from the
  7727. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7728. called immediately, to move the markers with the entries."
  7729. (setq org-markers-to-move nil)
  7730. (when (featurep 'org-clock)
  7731. (org-clock-save-markers-for-cut-and-paste beg end))
  7732. (when (featurep 'org-agenda)
  7733. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7734. (defun org-check-and-save-marker (marker beg end)
  7735. "Check if MARKER is between BEG and END.
  7736. If yes, remember the marker and the distance to BEG."
  7737. (when (and (marker-buffer marker)
  7738. (equal (marker-buffer marker) (current-buffer))
  7739. (>= marker beg) (< marker end))
  7740. (push (cons marker (- marker beg)) org-markers-to-move)))
  7741. (defun org-reinstall-markers-in-region (beg)
  7742. "Move all remembered markers to their position relative to BEG."
  7743. (mapc (lambda (x)
  7744. (move-marker (car x) (+ beg (cdr x))))
  7745. org-markers-to-move)
  7746. (setq org-markers-to-move nil))
  7747. (defun org-narrow-to-subtree ()
  7748. "Narrow buffer to the current subtree."
  7749. (interactive)
  7750. (save-excursion
  7751. (save-match-data
  7752. (org-with-limited-levels
  7753. (narrow-to-region
  7754. (progn (org-back-to-heading t) (point))
  7755. (progn (org-end-of-subtree t t)
  7756. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7757. (point)))))))
  7758. (defun org-narrow-to-block ()
  7759. "Narrow buffer to the current block."
  7760. (interactive)
  7761. (let* ((case-fold-search t)
  7762. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7763. "^[ \t]*#\\+end_.*")))
  7764. (if blockp
  7765. (narrow-to-region (car blockp) (cdr blockp))
  7766. (user-error "Not in a block"))))
  7767. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7768. "Clone the task (subtree) at point N times.
  7769. The clones will be inserted as siblings.
  7770. In interactive use, the user will be prompted for the number of
  7771. clones to be produced. If the entry has a timestamp, the user
  7772. will also be prompted for a time shift, which may be a repeater
  7773. as used in time stamps, for example `+3d'. To disable this,
  7774. you can call the function with a universal prefix argument.
  7775. When a valid repeater is given and the entry contains any time
  7776. stamps, the clones will become a sequence in time, with time
  7777. stamps in the subtree shifted for each clone produced. If SHIFT
  7778. is nil or the empty string, time stamps will be left alone. The
  7779. ID property of the original subtree is removed.
  7780. If the original subtree did contain time stamps with a repeater,
  7781. the following will happen:
  7782. - the repeater will be removed in each clone
  7783. - an additional clone will be produced, with the current, unshifted
  7784. date(s) in the entry.
  7785. - the original entry will be placed *after* all the clones, with
  7786. repeater intact.
  7787. - the start days in the repeater in the original entry will be shifted
  7788. to past the last clone.
  7789. In this way you can spell out a number of instances of a repeating task,
  7790. and still retain the repeater to cover future instances of the task.
  7791. As described above, N+1 clones are produced when the original
  7792. subtree has a repeater. Setting N to 0, then, can be used to
  7793. remove the repeater from a subtree and create a shifted clone
  7794. with the original repeater."
  7795. (interactive "nNumber of clones to produce: ")
  7796. (let ((shift
  7797. (or shift
  7798. (if (and (not (equal current-prefix-arg '(4)))
  7799. (save-excursion
  7800. (re-search-forward org-ts-regexp-both
  7801. (save-excursion
  7802. (org-end-of-subtree t)
  7803. (point)) t)))
  7804. (read-from-minibuffer
  7805. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7806. ""))) ;; No time shift
  7807. (n-no-remove -1)
  7808. (drawer-re org-drawer-regexp)
  7809. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  7810. beg end template task idprop
  7811. shift-n shift-what doshift nmin nmax)
  7812. (unless (wholenump n)
  7813. (user-error "Invalid number of replications %s" n))
  7814. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  7815. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7816. shift)))
  7817. (user-error "Invalid shift specification %s" shift))
  7818. (when doshift
  7819. (setq shift-n (string-to-number (match-string 1 shift))
  7820. shift-what (cdr (assoc (match-string 2 shift)
  7821. '(("d" . day) ("w" . week)
  7822. ("m" . month) ("y" . year))))))
  7823. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  7824. (setq nmin 1 nmax n)
  7825. (org-back-to-heading t)
  7826. (setq beg (point))
  7827. (setq idprop (org-entry-get nil "ID"))
  7828. (org-end-of-subtree t t)
  7829. (or (bolp) (insert "\n"))
  7830. (setq end (point))
  7831. (setq template (buffer-substring beg end))
  7832. (when (and doshift
  7833. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  7834. (delete-region beg end)
  7835. (setq end beg)
  7836. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  7837. (goto-char end)
  7838. (loop for n from nmin to nmax do
  7839. ;; prepare clone
  7840. (with-temp-buffer
  7841. (insert template)
  7842. (org-mode)
  7843. (goto-char (point-min))
  7844. (org-show-subtree)
  7845. (and idprop (if org-clone-delete-id
  7846. (org-entry-delete nil "ID")
  7847. (org-id-get-create t)))
  7848. (unless (= n 0)
  7849. (while (re-search-forward org-clock-re nil t)
  7850. (kill-whole-line))
  7851. (goto-char (point-min))
  7852. (while (re-search-forward drawer-re nil t)
  7853. (org-remove-empty-drawer-at (point))))
  7854. (goto-char (point-min))
  7855. (when doshift
  7856. (while (re-search-forward org-ts-regexp-both nil t)
  7857. (org-timestamp-change (* n shift-n) shift-what))
  7858. (unless (= n n-no-remove)
  7859. (goto-char (point-min))
  7860. (while (re-search-forward org-ts-regexp nil t)
  7861. (save-excursion
  7862. (goto-char (match-beginning 0))
  7863. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7864. (delete-region (match-beginning 1) (match-end 1)))))))
  7865. (setq task (buffer-string)))
  7866. (insert task))
  7867. (goto-char beg)))
  7868. ;;; Outline Sorting
  7869. (defun org-sort (with-case)
  7870. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7871. Optional argument WITH-CASE means sort case-sensitively."
  7872. (interactive "P")
  7873. (cond
  7874. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  7875. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  7876. (t
  7877. (org-call-with-arg 'org-sort-entries with-case))))
  7878. (defun org-sort-remove-invisible (s)
  7879. "Remove invisible links from string S."
  7880. (remove-text-properties 0 (length s) org-rm-props s)
  7881. (while (string-match org-bracket-link-regexp s)
  7882. (setq s (replace-match (if (match-end 2)
  7883. (match-string 3 s)
  7884. (match-string 1 s))
  7885. t t s)))
  7886. (let ((st (format " %s " s)))
  7887. (while (string-match org-emph-re st)
  7888. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  7889. (setq s (substring st 1 -1)))
  7890. s)
  7891. (defvar org-priority-regexp) ; defined later in the file
  7892. (defvar org-after-sorting-entries-or-items-hook nil
  7893. "Hook that is run after a bunch of entries or items have been sorted.
  7894. When children are sorted, the cursor is in the parent line when this
  7895. hook gets called. When a region or a plain list is sorted, the cursor
  7896. will be in the first entry of the sorted region/list.")
  7897. (defun org-sort-entries
  7898. (&optional with-case sorting-type getkey-func compare-func property)
  7899. "Sort entries on a certain level of an outline tree.
  7900. If there is an active region, the entries in the region are sorted.
  7901. Else, if the cursor is before the first entry, sort the top-level items.
  7902. Else, the children of the entry at point are sorted.
  7903. Sorting can be alphabetically, numerically, by date/time as given by
  7904. a time stamp, by a property, by priority order, or by a custom function.
  7905. The command prompts for the sorting type unless it has been given to the
  7906. function through the SORTING-TYPE argument, which needs to be a character,
  7907. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7908. the precise meaning of each character:
  7909. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7910. c By creation time, which is assumed to be the first inactive time stamp
  7911. at the beginning of a line.
  7912. d By deadline date/time.
  7913. k By clocking time.
  7914. n Numerically, by converting the beginning of the entry/item to a number.
  7915. o By order of TODO keywords.
  7916. p By priority according to the cookie.
  7917. r By the value of a property.
  7918. s By scheduled date/time.
  7919. t By date/time, either the first active time stamp in the entry, or, if
  7920. none exist, by the first inactive one.
  7921. Capital letters will reverse the sort order.
  7922. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7923. called with point at the beginning of the record. It must return either
  7924. a string or a number that should serve as the sorting key for that record.
  7925. Comparing entries ignores case by default. However, with an optional argument
  7926. WITH-CASE, the sorting considers case as well.
  7927. Sorting is done against the visible part of the headlines, it ignores hidden
  7928. links.
  7929. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  7930. (interactive "P")
  7931. (let ((case-func (if with-case 'identity 'downcase))
  7932. (cmstr
  7933. ;; The clock marker is lost when using `sort-subr', let's
  7934. ;; store the clocking string.
  7935. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  7936. (save-excursion
  7937. (goto-char org-clock-marker)
  7938. (buffer-substring-no-properties (line-beginning-position)
  7939. (point)))))
  7940. start beg end stars re re2
  7941. txt what tmp)
  7942. ;; Find beginning and end of region to sort
  7943. (cond
  7944. ((org-region-active-p)
  7945. ;; we will sort the region
  7946. (setq end (region-end)
  7947. what "region")
  7948. (goto-char (region-beginning))
  7949. (unless (org-at-heading-p) (outline-next-heading))
  7950. (setq start (point)))
  7951. ((or (org-at-heading-p)
  7952. (ignore-errors (progn (org-back-to-heading) t)))
  7953. ;; we will sort the children of the current headline
  7954. (org-back-to-heading)
  7955. (setq start (point)
  7956. end (progn (org-end-of-subtree t t)
  7957. (or (bolp) (insert "\n"))
  7958. (when (>= (org-back-over-empty-lines) 1)
  7959. (forward-line 1))
  7960. (point))
  7961. what "children")
  7962. (goto-char start)
  7963. (outline-show-subtree)
  7964. (outline-next-heading))
  7965. (t
  7966. ;; we will sort the top-level entries in this file
  7967. (goto-char (point-min))
  7968. (or (org-at-heading-p) (outline-next-heading))
  7969. (setq start (point))
  7970. (goto-char (point-max))
  7971. (beginning-of-line 1)
  7972. (when (looking-at ".*?\\S-")
  7973. ;; File ends in a non-white line
  7974. (end-of-line 1)
  7975. (insert "\n"))
  7976. (setq end (point-max))
  7977. (setq what "top-level")
  7978. (goto-char start)
  7979. (outline-show-all)))
  7980. (setq beg (point))
  7981. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7982. (looking-at "\\(\\*+\\)")
  7983. (setq stars (match-string 1)
  7984. re (concat "^" (regexp-quote stars) " +")
  7985. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7986. txt (buffer-substring beg end))
  7987. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7988. (when (and (not (equal stars "*")) (string-match re2 txt))
  7989. (user-error "Region to sort contains a level above the first entry"))
  7990. (unless sorting-type
  7991. (message
  7992. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7993. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7994. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7995. what)
  7996. (setq sorting-type (read-char-exclusive))
  7997. (unless getkey-func
  7998. (and (= (downcase sorting-type) ?f)
  7999. (setq getkey-func
  8000. (org-icompleting-read "Sort using function: "
  8001. obarray 'fboundp t nil nil))
  8002. (setq getkey-func (intern getkey-func))))
  8003. (and (= (downcase sorting-type) ?r)
  8004. (not property)
  8005. (setq property
  8006. (org-icompleting-read "Property: "
  8007. (mapcar 'list (org-buffer-property-keys t))
  8008. nil t))))
  8009. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8010. (message "Sorting entries...")
  8011. (save-restriction
  8012. (narrow-to-region start end)
  8013. (let ((dcst (downcase sorting-type))
  8014. (case-fold-search nil)
  8015. (now (current-time)))
  8016. (sort-subr
  8017. (/= dcst sorting-type)
  8018. ;; This function moves to the beginning character of the "record" to
  8019. ;; be sorted.
  8020. (lambda nil
  8021. (if (re-search-forward re nil t)
  8022. (goto-char (match-beginning 0))
  8023. (goto-char (point-max))))
  8024. ;; This function moves to the last character of the "record" being
  8025. ;; sorted.
  8026. (lambda nil
  8027. (save-match-data
  8028. (condition-case nil
  8029. (outline-forward-same-level 1)
  8030. (error
  8031. (goto-char (point-max))))))
  8032. ;; This function returns the value that gets sorted against.
  8033. (lambda nil
  8034. (cond
  8035. ((= dcst ?n)
  8036. (if (looking-at org-complex-heading-regexp)
  8037. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8038. nil))
  8039. ((= dcst ?a)
  8040. (if (looking-at org-complex-heading-regexp)
  8041. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8042. nil))
  8043. ((= dcst ?k)
  8044. (or (get-text-property (point) :org-clock-minutes) 0))
  8045. ((= dcst ?t)
  8046. (let ((end (save-excursion (outline-next-heading) (point))))
  8047. (if (or (re-search-forward org-ts-regexp end t)
  8048. (re-search-forward org-ts-regexp-both end t))
  8049. (org-time-string-to-seconds (match-string 0))
  8050. (org-float-time now))))
  8051. ((= dcst ?c)
  8052. (let ((end (save-excursion (outline-next-heading) (point))))
  8053. (if (re-search-forward
  8054. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8055. end t)
  8056. (org-time-string-to-seconds (match-string 0))
  8057. (org-float-time now))))
  8058. ((= dcst ?s)
  8059. (let ((end (save-excursion (outline-next-heading) (point))))
  8060. (if (re-search-forward org-scheduled-time-regexp end t)
  8061. (org-time-string-to-seconds (match-string 1))
  8062. (org-float-time now))))
  8063. ((= dcst ?d)
  8064. (let ((end (save-excursion (outline-next-heading) (point))))
  8065. (if (re-search-forward org-deadline-time-regexp end t)
  8066. (org-time-string-to-seconds (match-string 1))
  8067. (org-float-time now))))
  8068. ((= dcst ?p)
  8069. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8070. (string-to-char (match-string 2))
  8071. org-default-priority))
  8072. ((= dcst ?r)
  8073. (or (org-entry-get nil property) ""))
  8074. ((= dcst ?o)
  8075. (when (looking-at org-complex-heading-regexp)
  8076. (let* ((m (match-string 2))
  8077. (s (if (member m org-done-keywords) '- '+)))
  8078. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8079. ((= dcst ?f)
  8080. (if getkey-func
  8081. (progn
  8082. (setq tmp (funcall getkey-func))
  8083. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8084. tmp)
  8085. (error "Invalid key function `%s'" getkey-func)))
  8086. (t (error "Invalid sorting type `%c'" sorting-type))))
  8087. nil
  8088. (cond
  8089. ((= dcst ?a) 'string<)
  8090. ((= dcst ?f) compare-func)
  8091. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8092. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8093. ;; Reset the clock marker if needed
  8094. (when cmstr
  8095. (save-excursion
  8096. (goto-char start)
  8097. (search-forward cmstr nil t)
  8098. (move-marker org-clock-marker (point))))
  8099. (message "Sorting entries...done")))
  8100. ;;; The orgstruct minor mode
  8101. ;; Define a minor mode which can be used in other modes in order to
  8102. ;; integrate the org-mode structure editing commands.
  8103. ;; This is really a hack, because the org-mode structure commands use
  8104. ;; keys which normally belong to the major mode. Here is how it
  8105. ;; works: The minor mode defines all the keys necessary to operate the
  8106. ;; structure commands, but wraps the commands into a function which
  8107. ;; tests if the cursor is currently at a headline or a plain list
  8108. ;; item. If that is the case, the structure command is used,
  8109. ;; temporarily setting many Org-mode variables like regular
  8110. ;; expressions for filling etc. However, when any of those keys is
  8111. ;; used at a different location, function uses `key-binding' to look
  8112. ;; up if the key has an associated command in another currently active
  8113. ;; keymap (minor modes, major mode, global), and executes that
  8114. ;; command. There might be problems if any of the keys is otherwise
  8115. ;; used as a prefix key.
  8116. (defcustom orgstruct-heading-prefix-regexp ""
  8117. "Regexp that matches the custom prefix of Org headlines in
  8118. orgstruct(++)-mode."
  8119. :group 'org
  8120. :version "24.4"
  8121. :package-version '(Org . "8.3")
  8122. :type 'regexp)
  8123. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8124. (defcustom orgstruct-setup-hook nil
  8125. "Hook run after orgstruct-mode-map is filled."
  8126. :group 'org
  8127. :version "24.4"
  8128. :package-version '(Org . "8.0")
  8129. :type 'hook)
  8130. (defvar orgstruct-initialized nil)
  8131. (defvar org-local-vars nil
  8132. "List of local variables, for use by `orgstruct-mode'.")
  8133. ;;;###autoload
  8134. (define-minor-mode orgstruct-mode
  8135. "Toggle the minor mode `orgstruct-mode'.
  8136. This mode is for using Org-mode structure commands in other
  8137. modes. The following keys behave as if Org-mode were active, if
  8138. the cursor is on a headline, or on a plain list item (both as
  8139. defined by Org-mode)."
  8140. nil " OrgStruct" (make-sparse-keymap)
  8141. (funcall (if orgstruct-mode
  8142. 'add-to-invisibility-spec
  8143. 'remove-from-invisibility-spec)
  8144. '(outline . t))
  8145. (when orgstruct-mode
  8146. (org-load-modules-maybe)
  8147. (unless orgstruct-initialized
  8148. (orgstruct-setup)
  8149. (setq orgstruct-initialized t))))
  8150. ;;;###autoload
  8151. (defun turn-on-orgstruct ()
  8152. "Unconditionally turn on `orgstruct-mode'."
  8153. (orgstruct-mode 1))
  8154. (defvar-local org-fb-vars nil)
  8155. (defun orgstruct++-mode (&optional arg)
  8156. "Toggle `orgstruct-mode', the enhanced version of it.
  8157. In addition to setting orgstruct-mode, this also exports all
  8158. indentation and autofilling variables from org-mode into the
  8159. buffer. It will also recognize item context in multiline items."
  8160. (interactive "P")
  8161. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8162. (if (< arg 1)
  8163. (progn (orgstruct-mode -1)
  8164. (mapc (lambda(v)
  8165. (set (make-local-variable (car v))
  8166. (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
  8167. org-fb-vars))
  8168. (orgstruct-mode 1)
  8169. (setq org-fb-vars nil)
  8170. (unless org-local-vars
  8171. (setq org-local-vars (org-get-local-variables)))
  8172. (let (var val)
  8173. (mapc
  8174. (lambda (x)
  8175. (when (string-match
  8176. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
  8177. (symbol-name (car x)))
  8178. (setq var (car x) val (nth 1 x))
  8179. (push (list var `(quote ,(eval var))) org-fb-vars)
  8180. (set (make-local-variable var)
  8181. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8182. org-local-vars)
  8183. (setq-local orgstruct-is-++ t))))
  8184. (defvar-local orgstruct-is-++ nil
  8185. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8186. ;;;###autoload
  8187. (defun turn-on-orgstruct++ ()
  8188. "Unconditionally turn on `orgstruct++-mode'."
  8189. (orgstruct++-mode 1))
  8190. (defun orgstruct-error ()
  8191. "Error when there is no default binding for a structure key."
  8192. (interactive)
  8193. (funcall (if (fboundp 'user-error)
  8194. 'user-error
  8195. 'error)
  8196. "This key has no function outside structure elements"))
  8197. (defun orgstruct-setup ()
  8198. "Setup orgstruct keymap."
  8199. (dolist (cell '((org-demote . t)
  8200. (org-metaleft . t)
  8201. (org-metaright . t)
  8202. (org-promote . t)
  8203. (org-shiftmetaleft . t)
  8204. (org-shiftmetaright . t)
  8205. org-backward-element
  8206. org-backward-heading-same-level
  8207. org-ctrl-c-ret
  8208. org-ctrl-c-minus
  8209. org-ctrl-c-star
  8210. org-cycle
  8211. org-forward-heading-same-level
  8212. org-insert-heading
  8213. org-insert-heading-respect-content
  8214. org-kill-note-or-show-branches
  8215. org-mark-subtree
  8216. org-meta-return
  8217. org-metadown
  8218. org-metaup
  8219. org-narrow-to-subtree
  8220. org-promote-subtree
  8221. org-reveal
  8222. org-shiftdown
  8223. org-shiftleft
  8224. org-shiftmetadown
  8225. org-shiftmetaup
  8226. org-shiftright
  8227. org-shifttab
  8228. org-shifttab
  8229. org-shiftup
  8230. org-show-children
  8231. org-show-subtree
  8232. org-sort
  8233. org-up-element
  8234. outline-demote
  8235. outline-next-visible-heading
  8236. outline-previous-visible-heading
  8237. outline-promote
  8238. outline-up-heading))
  8239. (let ((f (or (car-safe cell) cell))
  8240. (disable-when-heading-prefix (cdr-safe cell)))
  8241. (when (fboundp f)
  8242. (let ((new-bindings))
  8243. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8244. (where-is-internal f outline-mode-map)))
  8245. (push binding new-bindings)
  8246. ;; TODO use local-function-key-map
  8247. (dolist (rep '(("<tab>" . "TAB")
  8248. ("<return>" . "RET")
  8249. ("<escape>" . "ESC")
  8250. ("<delete>" . "DEL")))
  8251. (setq binding (read-kbd-macro
  8252. (let ((case-fold-search))
  8253. (replace-regexp-in-string
  8254. (regexp-quote (cdr rep))
  8255. (car rep)
  8256. (key-description binding)))))
  8257. (pushnew binding new-bindings :test 'equal)))
  8258. (dolist (binding new-bindings)
  8259. (let ((key (lookup-key orgstruct-mode-map binding)))
  8260. (when (or (not key) (numberp key))
  8261. (ignore-errors
  8262. (org-defkey orgstruct-mode-map
  8263. binding
  8264. (orgstruct-make-binding
  8265. f binding disable-when-heading-prefix))))))))))
  8266. (run-hooks 'orgstruct-setup-hook))
  8267. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8268. "Create a function for binding in the structure minor mode.
  8269. FUN is the command to call inside a table. KEY is the key that
  8270. should be checked in for a command to execute outside of tables.
  8271. Non-nil `disable-when-heading-prefix' means to disable the command
  8272. if `orgstruct-heading-prefix-regexp' is not empty."
  8273. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8274. (let ((nname name)
  8275. (i 0))
  8276. (while (fboundp (intern nname))
  8277. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8278. (setq name (intern nname)))
  8279. (eval
  8280. (let ((bindings '((org-heading-regexp
  8281. (concat "^"
  8282. orgstruct-heading-prefix-regexp
  8283. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8284. (org-outline-regexp
  8285. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8286. (org-outline-regexp-bol
  8287. (concat "^" org-outline-regexp))
  8288. (outline-regexp org-outline-regexp)
  8289. (outline-heading-end-regexp "\n")
  8290. (outline-level 'org-outline-level)
  8291. (outline-heading-alist))))
  8292. `(defun ,name (arg)
  8293. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8294. "Outside of structure, run the binding of `"
  8295. (key-description key) "'."
  8296. (when disable-when-heading-prefix
  8297. (concat
  8298. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8299. "back to the default binding due to limitations of Org's implementation of\n"
  8300. "`" (symbol-name fun) "'.")))
  8301. (interactive "p")
  8302. (let* ((disable
  8303. ,(and disable-when-heading-prefix
  8304. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8305. (fallback
  8306. (or disable
  8307. (not
  8308. (let* ,bindings
  8309. (org-context-p 'headline 'item
  8310. ,(when (memq fun
  8311. '(org-insert-heading
  8312. org-insert-heading-respect-content
  8313. org-meta-return))
  8314. '(when orgstruct-is-++
  8315. 'item-body))))))))
  8316. (if fallback
  8317. (let* ((orgstruct-mode)
  8318. (binding
  8319. (let ((key ,key))
  8320. (catch 'exit
  8321. (dolist
  8322. (rep
  8323. '(nil
  8324. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8325. ("<\\([^>]*\\)return>" . "\\1RET")
  8326. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8327. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8328. nil)
  8329. (when rep
  8330. (setq key (read-kbd-macro
  8331. (let ((case-fold-search))
  8332. (replace-regexp-in-string
  8333. (car rep)
  8334. (cdr rep)
  8335. (key-description key))))))
  8336. (when (key-binding key)
  8337. (throw 'exit (key-binding key))))))))
  8338. (if (keymapp binding)
  8339. (org-set-transient-map binding)
  8340. (let ((func (or binding
  8341. (unless disable
  8342. 'orgstruct-error))))
  8343. (when func
  8344. (call-interactively func)))))
  8345. (org-run-like-in-org-mode
  8346. (lambda ()
  8347. (interactive)
  8348. (let* ,bindings
  8349. (call-interactively ',fun)))))))))
  8350. name))
  8351. (defun org-contextualize-keys (alist contexts)
  8352. "Return valid elements in ALIST depending on CONTEXTS.
  8353. `org-agenda-custom-commands' or `org-capture-templates' are the
  8354. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8355. or `org-capture-templates-contexts' are the associated contexts
  8356. definitions."
  8357. (let ((contexts
  8358. ;; normalize contexts
  8359. (mapcar
  8360. (lambda(c) (cond ((listp (cadr c))
  8361. (list (car c) (car c) (cadr c)))
  8362. ((string= "" (cadr c))
  8363. (list (car c) (car c) (caddr c)))
  8364. (t c)))
  8365. contexts))
  8366. (a alist) r s)
  8367. ;; loop over all commands or templates
  8368. (dolist (c a)
  8369. (let (vrules repl)
  8370. (cond
  8371. ((not (assoc (car c) contexts))
  8372. (push c r))
  8373. ((and (assoc (car c) contexts)
  8374. (setq vrules (org-contextualize-validate-key
  8375. (car c) contexts)))
  8376. (mapc (lambda (vr)
  8377. (unless (equal (car vr) (cadr vr))
  8378. (setq repl vr)))
  8379. vrules)
  8380. (if (not repl) (push c r)
  8381. (push (cadr repl) s)
  8382. (push
  8383. (cons (car c)
  8384. (cdr (or (assoc (cadr repl) alist)
  8385. (error "Undefined key `%s' as contextual replacement for `%s'"
  8386. (cadr repl) (car c)))))
  8387. r))))))
  8388. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8389. (delq
  8390. nil
  8391. (delete-dups
  8392. (mapcar (lambda (x)
  8393. (let ((tpl (car x)))
  8394. (unless (delq
  8395. nil
  8396. (mapcar (lambda (y)
  8397. (equal y tpl))
  8398. s))
  8399. x)))
  8400. (reverse r))))))
  8401. (defun org-contextualize-validate-key (key contexts)
  8402. "Check CONTEXTS for agenda or capture KEY."
  8403. (let (rr res)
  8404. (dolist (r contexts)
  8405. (mapc
  8406. (lambda (rr)
  8407. (when
  8408. (and (equal key (car r))
  8409. (if (functionp rr) (funcall rr)
  8410. (or (and (eq (car rr) 'in-file)
  8411. (buffer-file-name)
  8412. (string-match (cdr rr) (buffer-file-name)))
  8413. (and (eq (car rr) 'in-mode)
  8414. (string-match (cdr rr) (symbol-name major-mode)))
  8415. (and (eq (car rr) 'in-buffer)
  8416. (string-match (cdr rr) (buffer-name)))
  8417. (when (and (eq (car rr) 'not-in-file)
  8418. (buffer-file-name))
  8419. (not (string-match (cdr rr) (buffer-file-name))))
  8420. (when (eq (car rr) 'not-in-mode)
  8421. (not (string-match (cdr rr) (symbol-name major-mode))))
  8422. (when (eq (car rr) 'not-in-buffer)
  8423. (not (string-match (cdr rr) (buffer-name)))))))
  8424. (push r res)))
  8425. (car (last r))))
  8426. (delete-dups (delq nil res))))
  8427. (defun org-context-p (&rest contexts)
  8428. "Check if local context is any of CONTEXTS.
  8429. Possible values in the list of contexts are `table', `headline', and `item'."
  8430. (let ((pos (point)))
  8431. (goto-char (point-at-bol))
  8432. (prog1 (or (and (memq 'table contexts)
  8433. (looking-at "[ \t]*|"))
  8434. (and (memq 'headline contexts)
  8435. (looking-at org-outline-regexp))
  8436. (and (memq 'item contexts)
  8437. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8438. (and (memq 'item-body contexts)
  8439. (org-in-item-p)))
  8440. (goto-char pos))))
  8441. (defun org-get-local-variables ()
  8442. "Return a list of all local variables in an Org mode buffer."
  8443. (let (varlist)
  8444. (with-current-buffer (get-buffer-create "*Org tmp*")
  8445. (erase-buffer)
  8446. (org-mode)
  8447. (setq varlist (buffer-local-variables)))
  8448. (kill-buffer "*Org tmp*")
  8449. (delq nil
  8450. (mapcar
  8451. (lambda (x)
  8452. (setq x
  8453. (if (symbolp x)
  8454. (list x)
  8455. (list (car x) (cdr x))))
  8456. (if (and (not (get (car x) 'org-state))
  8457. (string-match
  8458. "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8459. (symbol-name (car x))))
  8460. x nil))
  8461. varlist))))
  8462. (defun org-clone-local-variables (from-buffer &optional regexp)
  8463. "Clone local variables from FROM-BUFFER.
  8464. Optional argument REGEXP selects variables to clone."
  8465. (mapc
  8466. (lambda (pair)
  8467. (and (symbolp (car pair))
  8468. (or (null regexp)
  8469. (string-match regexp (symbol-name (car pair))))
  8470. (set (make-local-variable (car pair))
  8471. (cdr pair))))
  8472. (buffer-local-variables from-buffer)))
  8473. ;;;###autoload
  8474. (defun org-run-like-in-org-mode (cmd)
  8475. "Run a command, pretending that the current buffer is in Org-mode.
  8476. This will temporarily bind local variables that are typically bound in
  8477. Org-mode to the values they have in Org-mode, and then interactively
  8478. call CMD."
  8479. (org-load-modules-maybe)
  8480. (unless org-local-vars
  8481. (setq org-local-vars (org-get-local-variables)))
  8482. (let (binds)
  8483. (dolist (var org-local-vars)
  8484. (when (or (not (boundp (car var)))
  8485. (eq (symbol-value (car var))
  8486. (default-value (car var))))
  8487. (push (list (car var) `(quote ,(cadr var))) binds)))
  8488. (eval `(let ,binds
  8489. (call-interactively (quote ,cmd))))))
  8490. (defun org-get-category (&optional pos force-refresh)
  8491. "Get the category applying to position POS."
  8492. (save-match-data
  8493. (when force-refresh (org-refresh-category-properties))
  8494. (let ((pos (or pos (point))))
  8495. (or (get-text-property pos 'org-category)
  8496. (progn (org-refresh-category-properties)
  8497. (get-text-property pos 'org-category))))))
  8498. ;;; Refresh properties
  8499. (defun org-refresh-properties (dprop tprop)
  8500. "Refresh buffer text properties.
  8501. DPROP is the drawer property and TPROP is either the
  8502. corresponding text property to set, or an alist with each element
  8503. being a text property (as a symbol) and a function to apply to
  8504. the value of the drawer property."
  8505. (let ((case-fold-search t)
  8506. (inhibit-read-only t))
  8507. (org-with-silent-modifications
  8508. (save-excursion
  8509. (save-restriction
  8510. (widen)
  8511. (goto-char (point-min))
  8512. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8513. (org-refresh-property tprop (org-match-string-no-properties 1))))))))
  8514. (defun org-refresh-property (tprop p)
  8515. "Refresh the buffer text property TPROP from the drawer property P.
  8516. The refresh happens only for the current tree (not subtree)."
  8517. (unless (org-before-first-heading-p)
  8518. (save-excursion
  8519. (org-back-to-heading t)
  8520. (if (symbolp tprop)
  8521. ;; TPROP is a text property symbol
  8522. (put-text-property
  8523. (point) (or (outline-next-heading) (point-max)) tprop p)
  8524. ;; TPROP is an alist with (properties . function) elements
  8525. (dolist (al tprop)
  8526. (save-excursion
  8527. (put-text-property
  8528. (line-beginning-position) (or (outline-next-heading) (point-max))
  8529. (car al)
  8530. (funcall (cdr al) p))))))))
  8531. (defun org-refresh-category-properties ()
  8532. "Refresh category text properties in the buffer."
  8533. (let ((case-fold-search t)
  8534. (inhibit-read-only t)
  8535. (default-category
  8536. (cond ((null org-category)
  8537. (if buffer-file-name
  8538. (file-name-sans-extension
  8539. (file-name-nondirectory buffer-file-name))
  8540. "???"))
  8541. ((symbolp org-category) (symbol-name org-category))
  8542. (t org-category))))
  8543. (org-with-silent-modifications
  8544. (org-with-wide-buffer
  8545. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8546. ;; This is the default category for the buffer. If none is
  8547. ;; found, fall-back to `org-category' or buffer file name.
  8548. (put-text-property
  8549. (point-min) (point-max)
  8550. 'org-category
  8551. (catch 'buffer-category
  8552. (goto-char (point-max))
  8553. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8554. (let ((element (org-element-at-point)))
  8555. (when (eq (org-element-type element) 'keyword)
  8556. (throw 'buffer-category
  8557. (org-element-property :value element)))))
  8558. default-category))
  8559. ;; Set sub-tree specific categories.
  8560. (goto-char (point-min))
  8561. (let ((regexp (org-re-property "CATEGORY")))
  8562. (while (re-search-forward regexp nil t)
  8563. (let ((value (org-match-string-no-properties 3)))
  8564. (when (org-at-property-p)
  8565. (put-text-property
  8566. (save-excursion (org-back-to-heading t) (point))
  8567. (save-excursion (org-end-of-subtree t t) (point))
  8568. 'org-category
  8569. value)))))))))
  8570. (defun org-refresh-stats-properties ()
  8571. "Refresh stats text properties in the buffer."
  8572. (let (stats)
  8573. (org-with-silent-modifications
  8574. (save-excursion
  8575. (save-restriction
  8576. (widen)
  8577. (goto-char (point-min))
  8578. (while (re-search-forward
  8579. (concat org-outline-regexp-bol ".*"
  8580. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8581. nil t)
  8582. (setq stats (cond ((equal (match-string 3) "0") 0)
  8583. ((match-string 2)
  8584. (/ (* (string-to-number (match-string 2)) 100)
  8585. (string-to-number (match-string 3))))
  8586. (t (string-to-number (match-string 1)))))
  8587. (org-back-to-heading t)
  8588. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8589. 'org-stats stats)))))))
  8590. (defun org-refresh-effort-properties ()
  8591. "Refresh effort properties"
  8592. (org-refresh-properties
  8593. org-effort-property
  8594. '((effort . identity)
  8595. (effort-minutes . org-duration-string-to-minutes))))
  8596. ;;;; Link Stuff
  8597. ;;; Link abbreviations
  8598. (defun org-link-expand-abbrev (link)
  8599. "Apply replacements as defined in `org-link-abbrev-alist'."
  8600. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8601. (let* ((key (match-string 1 link))
  8602. (as (or (assoc key org-link-abbrev-alist-local)
  8603. (assoc key org-link-abbrev-alist)))
  8604. (tag (and (match-end 2) (match-string 3 link)))
  8605. rpl)
  8606. (if (not as)
  8607. link
  8608. (setq rpl (cdr as))
  8609. (cond
  8610. ((symbolp rpl) (funcall rpl tag))
  8611. ((string-match "%(\\([^)]+\\))" rpl)
  8612. (replace-match
  8613. (save-match-data
  8614. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8615. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8616. ((string-match "%h" rpl)
  8617. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8618. (t (concat rpl tag)))))
  8619. link))
  8620. ;;; Storing and inserting links
  8621. (defvar org-insert-link-history nil
  8622. "Minibuffer history for links inserted with `org-insert-link'.")
  8623. (defvar org-stored-links nil
  8624. "Contains the links stored with `org-store-link'.")
  8625. (defvar org-store-link-plist nil
  8626. "Plist with info about the most recently link created with `org-store-link'.")
  8627. (defvar org-link-protocols nil
  8628. "Link protocols added to Org-mode using `org-add-link-type'.")
  8629. (defvar org-store-link-functions nil
  8630. "List of functions that are called to create and store a link.
  8631. Each function will be called in turn until one returns a non-nil
  8632. value. Each function should check if it is responsible for creating
  8633. this link (for example by looking at the major mode).
  8634. If not, it must exit and return nil.
  8635. If yes, it should return a non-nil value after a calling
  8636. `org-store-link-props' with a list of properties and values.
  8637. Special properties are:
  8638. :type The link prefix, like \"http\". This must be given.
  8639. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8640. This is obligatory as well.
  8641. :description Optional default description for the second pair
  8642. of brackets in an Org-mode link. The user can still change
  8643. this when inserting this link into an Org-mode buffer.
  8644. In addition to these, any additional properties can be specified
  8645. and then used in capture templates.")
  8646. (defun org-add-link-type (type &optional follow export)
  8647. "Add TYPE to the list of `org-link-types'.
  8648. Re-compute all regular expressions depending on `org-link-types'
  8649. FOLLOW and EXPORT are two functions.
  8650. FOLLOW should take the link path as the single argument and do whatever
  8651. is necessary to follow the link, for example find a file or display
  8652. a mail message.
  8653. EXPORT should format the link path for export to one of the export formats.
  8654. It should be a function accepting three arguments:
  8655. path the path of the link, the text after the prefix (like \"http:\")
  8656. desc the description of the link, if any
  8657. format the export format, a symbol like `html' or `latex' or `ascii'.
  8658. The function may use the FORMAT information to return different values
  8659. depending on the format. The return value will be put literally into
  8660. the exported file. If the return value is nil, this means Org should
  8661. do what it normally does with links which do not have EXPORT defined.
  8662. Org mode has a built-in default for exporting links. If you are happy with
  8663. this default, there is no need to define an export function for the link
  8664. type. For a simple example of an export function, see `org-bbdb.el'."
  8665. (add-to-list 'org-link-types type t)
  8666. (org-make-link-regexps)
  8667. (org-element-update-syntax)
  8668. (if (assoc type org-link-protocols)
  8669. (setcdr (assoc type org-link-protocols) (list follow export))
  8670. (push (list type follow export) org-link-protocols)))
  8671. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8672. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8673. ;;;###autoload
  8674. (defun org-store-link (arg)
  8675. "\\<org-mode-map>Store an org-link to the current location.
  8676. This link is added to `org-stored-links' and can later be inserted
  8677. into an Org buffer with \\[org-insert-link].
  8678. For some link types, a prefix ARG is interpreted.
  8679. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8680. For file links, ARG negates `org-context-in-file-links'.
  8681. A double prefix ARG force skipping storing functions that are not
  8682. part of Org's core.
  8683. A triple prefix ARG force storing a link for each line in the
  8684. active region."
  8685. (interactive "P")
  8686. (org-load-modules-maybe)
  8687. (if (and (equal arg '(64)) (org-region-active-p))
  8688. (save-excursion
  8689. (let ((end (region-end)))
  8690. (goto-char (region-beginning))
  8691. (set-mark (point))
  8692. (while (< (point-at-eol) end)
  8693. (move-end-of-line 1) (activate-mark)
  8694. (let (current-prefix-arg)
  8695. (call-interactively 'org-store-link))
  8696. (move-beginning-of-line 2)
  8697. (set-mark (point)))))
  8698. (org-with-limited-levels
  8699. (setq org-store-link-plist nil)
  8700. (let (link cpltxt desc description search
  8701. txt custom-id agenda-link sfuns sfunsn)
  8702. (cond
  8703. ;; Store a link using an external link type
  8704. ((and (not (equal arg '(16)))
  8705. (setq sfuns
  8706. (delq
  8707. nil (mapcar (lambda (f)
  8708. (let (fs) (if (funcall f) (push f fs))))
  8709. org-store-link-functions))
  8710. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8711. (or (and (cdr sfuns)
  8712. (funcall (intern
  8713. (completing-read
  8714. "Which function for creating the link? "
  8715. sfunsn nil t (car sfunsn)))))
  8716. (funcall (caar sfuns)))
  8717. (setq link (plist-get org-store-link-plist :link)
  8718. desc (or (plist-get org-store-link-plist
  8719. :description)
  8720. link))))
  8721. ;; Store a link from a source code buffer.
  8722. ((org-src-edit-buffer-p)
  8723. (cond
  8724. ((save-excursion
  8725. (beginning-of-line)
  8726. (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
  8727. "[ \t]*$")))
  8728. (setq link (format "(%s)" (org-match-string-no-properties 1))))
  8729. ((org-called-interactively-p 'any)
  8730. (let (label)
  8731. (while (or (not label)
  8732. (org-with-wide-buffer
  8733. (goto-char (point-min))
  8734. (re-search-forward
  8735. (regexp-quote (format org-coderef-label-format label))
  8736. nil t)))
  8737. (when label (message "Label exists already") (sit-for 2))
  8738. (setq label (read-string "Code line label: " label)))
  8739. (end-of-line)
  8740. (setq link (format org-coderef-label-format label))
  8741. (let ((gc (- 79 (length link))))
  8742. (if (< (current-column) gc) (org-move-to-column gc t)
  8743. (insert " ")))
  8744. (insert link)
  8745. (setq link (concat "(" label ")") desc nil)))
  8746. (t (setq link nil))))
  8747. ;; We are in the agenda, link to referenced location
  8748. ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8749. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8750. (get-text-property (point) 'org-marker))))
  8751. (when m
  8752. (org-with-point-at m
  8753. (setq agenda-link
  8754. (if (org-called-interactively-p 'any)
  8755. (call-interactively 'org-store-link)
  8756. (org-store-link nil)))))))
  8757. ((eq major-mode 'calendar-mode)
  8758. (let ((cd (calendar-cursor-to-date)))
  8759. (setq link
  8760. (format-time-string
  8761. (car org-time-stamp-formats)
  8762. (apply 'encode-time
  8763. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8764. nil nil nil))))
  8765. (org-store-link-props :type "calendar" :date cd)))
  8766. ((eq major-mode 'help-mode)
  8767. (setq link (concat "help:" (save-excursion
  8768. (goto-char (point-min))
  8769. (looking-at "^[^ ]+")
  8770. (match-string 0))))
  8771. (org-store-link-props :type "help"))
  8772. ((eq major-mode 'w3-mode)
  8773. (setq cpltxt (if (and (buffer-name)
  8774. (not (string-match "Untitled" (buffer-name))))
  8775. (buffer-name)
  8776. (url-view-url t))
  8777. link (url-view-url t))
  8778. (org-store-link-props :type "w3" :url (url-view-url t)))
  8779. ((eq major-mode 'image-mode)
  8780. (setq cpltxt (concat "file:"
  8781. (abbreviate-file-name buffer-file-name))
  8782. link cpltxt)
  8783. (org-store-link-props :type "image" :file buffer-file-name))
  8784. ;; In dired, store a link to the file of the current line
  8785. ((derived-mode-p 'dired-mode)
  8786. (let ((file (dired-get-filename nil t)))
  8787. (setq file (if file
  8788. (abbreviate-file-name
  8789. (expand-file-name (dired-get-filename nil t)))
  8790. ;; otherwise, no file so use current directory.
  8791. default-directory))
  8792. (setq cpltxt (concat "file:" file)
  8793. link cpltxt)))
  8794. ((setq search (run-hook-with-args-until-success
  8795. 'org-create-file-search-functions))
  8796. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8797. "::" search))
  8798. (setq cpltxt (or description link)))
  8799. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8800. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8801. (cond
  8802. ;; Store a link using the target at point
  8803. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8804. (setq cpltxt
  8805. (concat "file:"
  8806. (abbreviate-file-name
  8807. (buffer-file-name (buffer-base-buffer)))
  8808. "::" (match-string 1))
  8809. link cpltxt))
  8810. ((and (featurep 'org-id)
  8811. (or (eq org-id-link-to-org-use-id t)
  8812. (and (org-called-interactively-p 'any)
  8813. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8814. (and (eq org-id-link-to-org-use-id
  8815. 'create-if-interactive-and-no-custom-id)
  8816. (not custom-id))))
  8817. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8818. ;; Store a link using the ID at point
  8819. (setq link (condition-case nil
  8820. (prog1 (org-id-store-link)
  8821. (setq desc (or (plist-get org-store-link-plist
  8822. :description)
  8823. "")))
  8824. (error
  8825. ;; Probably before first headline, link only to file
  8826. (concat "file:"
  8827. (abbreviate-file-name
  8828. (buffer-file-name (buffer-base-buffer))))))))
  8829. (t
  8830. ;; Just link to current headline
  8831. (setq cpltxt (concat "file:"
  8832. (abbreviate-file-name
  8833. (buffer-file-name (buffer-base-buffer)))))
  8834. ;; Add a context search string
  8835. (when (org-xor org-context-in-file-links arg)
  8836. (let* ((ee (org-element-at-point))
  8837. (et (org-element-type ee))
  8838. (ev (plist-get (cadr ee) :value))
  8839. (ek (plist-get (cadr ee) :key))
  8840. (eok (and (stringp ek) (string-match "name" ek))))
  8841. (setq txt (cond
  8842. ((org-at-heading-p) nil)
  8843. ((and (eq et 'keyword) eok) ev)
  8844. ((org-region-active-p)
  8845. (buffer-substring (region-beginning) (region-end)))))
  8846. (when (or (null txt) (string-match "\\S-" txt))
  8847. (setq cpltxt
  8848. (concat cpltxt "::"
  8849. (condition-case nil
  8850. (org-make-org-heading-search-string txt)
  8851. (error "")))
  8852. desc (or (and (eq et 'keyword) eok ev)
  8853. (nth 4 (ignore-errors (org-heading-components)))
  8854. "NONE")))))
  8855. (when (string-match "::\\'" cpltxt)
  8856. (setq cpltxt (substring cpltxt 0 -2)))
  8857. (setq link cpltxt))))
  8858. ((buffer-file-name (buffer-base-buffer))
  8859. ;; Just link to this file here.
  8860. (setq cpltxt (concat "file:"
  8861. (abbreviate-file-name
  8862. (buffer-file-name (buffer-base-buffer)))))
  8863. ;; Add a context string.
  8864. (when (org-xor org-context-in-file-links arg)
  8865. (setq txt (if (org-region-active-p)
  8866. (buffer-substring (region-beginning) (region-end))
  8867. (buffer-substring (point-at-bol) (point-at-eol))))
  8868. ;; Only use search option if there is some text.
  8869. (when (string-match "\\S-" txt)
  8870. (setq cpltxt
  8871. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8872. desc "NONE")))
  8873. (setq link cpltxt))
  8874. ((org-called-interactively-p 'interactive)
  8875. (user-error "No method for storing a link from this buffer"))
  8876. (t (setq link nil)))
  8877. ;; We're done setting link and desc, clean up
  8878. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8879. (setq link (or link cpltxt)
  8880. desc (or desc cpltxt))
  8881. (cond ((equal desc "NONE") (setq desc nil))
  8882. ((and desc (string-match org-bracket-link-analytic-regexp desc))
  8883. (let ((d0 (match-string 3 desc))
  8884. (p0 (match-string 5 desc)))
  8885. (setq desc
  8886. (replace-regexp-in-string
  8887. org-bracket-link-regexp
  8888. (concat (or p0 d0)
  8889. (if (equal (length (match-string 0 desc))
  8890. (length desc)) "*" "")) desc)))))
  8891. ;; Return the link
  8892. (if (not (and (or (org-called-interactively-p 'any)
  8893. executing-kbd-macro)
  8894. link))
  8895. (or agenda-link (and link (org-make-link-string link desc)))
  8896. (push (list link desc) org-stored-links)
  8897. (message "Stored: %s" (or desc link))
  8898. (when custom-id
  8899. (setq link (concat "file:" (abbreviate-file-name
  8900. (buffer-file-name)) "::#" custom-id))
  8901. (push (list link desc) org-stored-links))
  8902. (car org-stored-links))))))
  8903. (defun org-store-link-props (&rest plist)
  8904. "Store link properties, extract names and addresses."
  8905. (let (x adr)
  8906. (when (setq x (plist-get plist :from))
  8907. (setq adr (mail-extract-address-components x))
  8908. (setq plist (plist-put plist :fromname (car adr)))
  8909. (setq plist (plist-put plist :fromaddress (nth 1 adr))))
  8910. (when (setq x (plist-get plist :to))
  8911. (setq adr (mail-extract-address-components x))
  8912. (setq plist (plist-put plist :toname (car adr)))
  8913. (setq plist (plist-put plist :toaddress (nth 1 adr)))))
  8914. (let ((from (plist-get plist :from))
  8915. (to (plist-get plist :to)))
  8916. (when (and from to org-from-is-user-regexp)
  8917. (setq plist
  8918. (plist-put plist :fromto
  8919. (if (string-match org-from-is-user-regexp from)
  8920. (concat "to %t")
  8921. (concat "from %f"))))))
  8922. (setq org-store-link-plist plist))
  8923. (defun org-add-link-props (&rest plist)
  8924. "Add these properties to the link property list."
  8925. (let (key value)
  8926. (while plist
  8927. (setq key (pop plist) value (pop plist))
  8928. (setq org-store-link-plist
  8929. (plist-put org-store-link-plist key value)))))
  8930. (defun org-email-link-description (&optional fmt)
  8931. "Return the description part of an email link.
  8932. This takes information from `org-store-link-plist' and formats it
  8933. according to FMT (default from `org-email-link-description-format')."
  8934. (setq fmt (or fmt org-email-link-description-format))
  8935. (let* ((p org-store-link-plist)
  8936. (to (plist-get p :toaddress))
  8937. (from (plist-get p :fromaddress))
  8938. (table
  8939. (list
  8940. (cons "%c" (plist-get p :fromto))
  8941. (cons "%F" (plist-get p :from))
  8942. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8943. (cons "%T" (plist-get p :to))
  8944. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8945. (cons "%s" (plist-get p :subject))
  8946. (cons "%d" (plist-get p :date))
  8947. (cons "%m" (plist-get p :message-id)))))
  8948. (when (string-match "%c" fmt)
  8949. ;; Check if the user wrote this message
  8950. (if (and org-from-is-user-regexp from to
  8951. (save-match-data (string-match org-from-is-user-regexp from)))
  8952. (setq fmt (replace-match "to %t" t t fmt))
  8953. (setq fmt (replace-match "from %f" t t fmt))))
  8954. (org-replace-escapes fmt table)))
  8955. (defun org-make-org-heading-search-string (&optional string)
  8956. "Make search string for the current headline or STRING."
  8957. (let ((s (or string
  8958. (and (derived-mode-p 'org-mode)
  8959. (save-excursion
  8960. (org-back-to-heading t)
  8961. (org-element-property :raw-value (org-element-at-point))))))
  8962. (lines org-context-in-file-links))
  8963. (or string (setq s (concat "*" s))) ; Add * for headlines
  8964. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8965. (when (and string (integerp lines) (> lines 0))
  8966. (let ((slines (org-split-string s "\n")))
  8967. (when (< lines (length slines))
  8968. (setq s (mapconcat
  8969. 'identity
  8970. (reverse (nthcdr (- (length slines) lines)
  8971. (reverse slines))) "\n")))))
  8972. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  8973. (defun org-make-link-string (link &optional description)
  8974. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8975. (unless (org-string-nw-p link) (error "Empty link"))
  8976. (let ((uri (cond ((string-match org-link-types-re link)
  8977. (concat (match-string 1 link)
  8978. (org-link-escape (substring link (match-end 1)))))
  8979. ;; For readability, url-encode internal links only
  8980. ;; when absolutely needed (i.e, when they contain
  8981. ;; square brackets). File links however, are
  8982. ;; encoded since, e.g., spaces are significant.
  8983. ((or (file-name-absolute-p link)
  8984. (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
  8985. (org-link-escape link))
  8986. (t link)))
  8987. (description
  8988. (and (org-string-nw-p description)
  8989. ;; Remove brackets from description, as they are fatal.
  8990. (replace-regexp-in-string
  8991. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8992. (org-trim description)))))
  8993. (format "[[%s]%s]"
  8994. uri
  8995. (if description (format "[%s]" description) ""))))
  8996. (defconst org-link-escape-chars
  8997. ;;%20 %5B %5D %25
  8998. '(?\s ?\[ ?\] ?%)
  8999. "List of characters that should be escaped in a link when stored to Org.
  9000. This is the list that is used for internal purposes.")
  9001. (defconst org-link-escape-chars-browser
  9002. ;;%20 %22
  9003. '(?\s ?\")
  9004. "List of characters to be escaped before handing over to the browser.
  9005. If you consider using this constant then you probably want to use
  9006. the function `org-link-escape-browser' instead. See there why
  9007. this constant is a candidate to be removed once Org drops support
  9008. for Emacs 24.1 and 24.2.")
  9009. (defun org-link-escape (text &optional table merge)
  9010. "Return percent escaped representation of TEXT.
  9011. TEXT is a string with the text to escape.
  9012. Optional argument TABLE is a list with characters that should be
  9013. escaped. When nil, `org-link-escape-chars' is used.
  9014. If optional argument MERGE is set, merge TABLE into
  9015. `org-link-escape-chars'."
  9016. (let ((characters-to-encode
  9017. (cond ((null table) org-link-escape-chars)
  9018. (merge (append org-link-escape-chars table))
  9019. (t table))))
  9020. (mapconcat
  9021. (lambda (c)
  9022. (if (or (memq c characters-to-encode)
  9023. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9024. (mapconcat (lambda (e) (format "%%%.2X" e))
  9025. (or (encode-coding-char c 'utf-8)
  9026. (error "Unable to percent escape character: %c" c))
  9027. "")
  9028. (char-to-string c)))
  9029. text "")))
  9030. (defun org-link-escape-browser (text)
  9031. "Escape some characters before handing over to the browser.
  9032. This function is a candidate to be removed together with the
  9033. constant `org-link-escape-chars-browser' once Org drops support
  9034. for Emacs 24.1 and 24.2. All calls to this function will have to
  9035. be replaced with `url-encode-url' which is available since Emacs
  9036. 24.3.1."
  9037. ;; Example with the Org link
  9038. ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
  9039. ;; to open the browser with +subject:"Release 8.2" filled into the
  9040. ;; query field: In this case the variable TEXT contains the
  9041. ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
  9042. ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
  9043. ;; `org-link-escape' with `org-link-escape-chars-browser' converts
  9044. ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
  9045. (if (fboundp 'url-encode-url)
  9046. (url-encode-url text)
  9047. (if (org-string-match-p
  9048. (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
  9049. text)
  9050. (org-link-escape text org-link-escape-chars-browser)
  9051. text)))
  9052. (defun org-link-unescape (str)
  9053. "Unhex hexified Unicode parts in string STR.
  9054. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9055. reciprocal of `org-link-escape', which see."
  9056. (if (org-string-nw-p str)
  9057. (replace-regexp-in-string
  9058. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9059. str))
  9060. (defun org-link-unescape-compound (hex)
  9061. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9062. Note: this function also decodes single byte encodings like
  9063. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9064. (save-match-data
  9065. (let* ((bytes (cdr (split-string hex "%")))
  9066. (ret "")
  9067. (eat 0)
  9068. (sum 0))
  9069. (while bytes
  9070. (let* ((val (string-to-number (pop bytes) 16))
  9071. (shift-xor
  9072. (if (= 0 eat)
  9073. (cond
  9074. ((>= val 252) (cons 6 252))
  9075. ((>= val 248) (cons 5 248))
  9076. ((>= val 240) (cons 4 240))
  9077. ((>= val 224) (cons 3 224))
  9078. ((>= val 192) (cons 2 192))
  9079. (t (cons 0 0)))
  9080. (cons 6 128))))
  9081. (when (>= val 192) (setq eat (car shift-xor)))
  9082. (setq val (logxor val (cdr shift-xor)))
  9083. (setq sum (+ (lsh sum (car shift-xor)) val))
  9084. (when (> eat 0) (setq eat (- eat 1)))
  9085. (cond
  9086. ((= 0 eat) ;multi byte
  9087. (setq ret (concat ret (org-char-to-string sum)))
  9088. (setq sum 0))
  9089. ((not bytes) ; single byte(s)
  9090. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9091. ret)))
  9092. (defun org-link-unescape-single-byte-sequence (hex)
  9093. "Unhexify hex-encoded single byte character sequences."
  9094. (mapconcat (lambda (byte)
  9095. (char-to-string (string-to-number byte 16)))
  9096. (cdr (split-string hex "%")) ""))
  9097. (defun org-xor (a b)
  9098. "Exclusive or."
  9099. (if a (not b) b))
  9100. (defun org-fixup-message-id-for-http (s)
  9101. "Replace special characters in a message id, so it can be used in an http query."
  9102. (when (string-match "%" s)
  9103. (setq s (mapconcat (lambda (c)
  9104. (if (eq c ?%)
  9105. "%25"
  9106. (char-to-string c)))
  9107. s "")))
  9108. (while (string-match "<" s)
  9109. (setq s (replace-match "%3C" t t s)))
  9110. (while (string-match ">" s)
  9111. (setq s (replace-match "%3E" t t s)))
  9112. (while (string-match "@" s)
  9113. (setq s (replace-match "%40" t t s)))
  9114. s)
  9115. (defun org-link-prettify (link)
  9116. "Return a human-readable representation of LINK.
  9117. The car of LINK must be a raw link.
  9118. The cdr of LINK must be either a link description or nil."
  9119. (let ((desc (or (cadr link) "<no description>")))
  9120. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9121. "<" (car link) ">")))
  9122. ;;;###autoload
  9123. (defun org-insert-link-global ()
  9124. "Insert a link like Org-mode does.
  9125. This command can be called in any mode to insert a link in Org-mode syntax."
  9126. (interactive)
  9127. (org-load-modules-maybe)
  9128. (org-run-like-in-org-mode 'org-insert-link))
  9129. (defun org-insert-all-links (arg &optional pre post)
  9130. "Insert all links in `org-stored-links'.
  9131. When a universal prefix, do not delete the links from `org-stored-links'.
  9132. When `ARG' is a number, insert the last N link(s).
  9133. `PRE' and `POST' are optional arguments to define a string to
  9134. prepend or to append."
  9135. (interactive "P")
  9136. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9137. (links (copy-seq org-stored-links))
  9138. (pr (or pre "- "))
  9139. (po (or post "\n"))
  9140. (cnt 1) l)
  9141. (if (null org-stored-links)
  9142. (message "No link to insert")
  9143. (while (and (or (listp arg) (>= arg cnt))
  9144. (setq l (if (listp arg)
  9145. (pop links)
  9146. (pop org-stored-links))))
  9147. (setq cnt (1+ cnt))
  9148. (insert pr)
  9149. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9150. (insert po)))))
  9151. (defun org-insert-last-stored-link (arg)
  9152. "Insert the last link stored in `org-stored-links'."
  9153. (interactive "p")
  9154. (org-insert-all-links arg "" "\n"))
  9155. (defun org-link-fontify-links-to-this-file ()
  9156. "Fontify links to the current file in `org-stored-links'."
  9157. (let ((f (buffer-file-name)) a b)
  9158. (setq a (mapcar (lambda(l)
  9159. (let ((ll (car l)))
  9160. (when (and (string-match "^file:\\(.+\\)::" ll)
  9161. (equal f (expand-file-name (match-string 1 ll))))
  9162. ll)))
  9163. org-stored-links))
  9164. (when (featurep 'org-id)
  9165. (setq b (mapcar (lambda(l)
  9166. (let ((ll (car l)))
  9167. (when (and (string-match "^id:\\(.+\\)$" ll)
  9168. (equal f (expand-file-name
  9169. (or (org-id-find-id-file
  9170. (match-string 1 ll)) ""))))
  9171. ll)))
  9172. org-stored-links)))
  9173. (mapcar (lambda(l)
  9174. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9175. (delq nil (append a b)))))
  9176. (defvar org-link-links-in-this-file nil)
  9177. (defun org-insert-link (&optional complete-file link-location default-description)
  9178. "Insert a link. At the prompt, enter the link.
  9179. Completion can be used to insert any of the link protocol prefixes like
  9180. http or ftp in use.
  9181. The history can be used to select a link previously stored with
  9182. `org-store-link'. When the empty string is entered (i.e. if you just
  9183. press RET at the prompt), the link defaults to the most recently
  9184. stored link. As SPC triggers completion in the minibuffer, you need to
  9185. use M-SPC or C-q SPC to force the insertion of a space character.
  9186. You will also be prompted for a description, and if one is given, it will
  9187. be displayed in the buffer instead of the link.
  9188. If there is already a link at point, this command will allow you to edit link
  9189. and description parts.
  9190. With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
  9191. be selected using completion. The path to the file will be relative to the
  9192. current directory if the file is in the current directory or a subdirectory.
  9193. Otherwise, the link will be the absolute path as completed in the minibuffer
  9194. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9195. option `org-link-file-path-type'.
  9196. With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
  9197. the current directory or below.
  9198. With three \\[universal-argument] prefixes, negate the meaning of
  9199. `org-keep-stored-link-after-insertion'.
  9200. If `org-make-link-description-function' is non-nil, this function will be
  9201. called with the link target, and the result will be the default
  9202. link description.
  9203. If the LINK-LOCATION parameter is non-nil, this value will be
  9204. used as the link location instead of reading one interactively.
  9205. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  9206. be used as the default description."
  9207. (interactive "P")
  9208. (let* ((wcf (current-window-configuration))
  9209. (origbuf (current-buffer))
  9210. (region (when (org-region-active-p)
  9211. (buffer-substring (region-beginning) (region-end))))
  9212. (remove (and region (list (region-beginning) (region-end))))
  9213. (desc region)
  9214. tmphist ; byte-compile incorrectly complains about this
  9215. (link link-location)
  9216. (abbrevs org-link-abbrev-alist-local)
  9217. entry file all-prefixes auto-desc)
  9218. (cond
  9219. (link-location) ; specified by arg, just use it.
  9220. ((org-in-regexp org-bracket-link-regexp 1)
  9221. ;; We do have a link at point, and we are going to edit it.
  9222. (setq remove (list (match-beginning 0) (match-end 0)))
  9223. (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
  9224. (setq link (read-string "Link: "
  9225. (org-link-unescape
  9226. (org-match-string-no-properties 1)))))
  9227. ((or (org-in-regexp org-angle-link-re)
  9228. (org-in-regexp org-plain-link-re))
  9229. ;; Convert to bracket link
  9230. (setq remove (list (match-beginning 0) (match-end 0))
  9231. link (read-string "Link: "
  9232. (org-remove-angle-brackets (match-string 0)))))
  9233. ((member complete-file '((4) (16)))
  9234. ;; Completing read for file names.
  9235. (setq link (org-file-complete-link complete-file)))
  9236. (t
  9237. ;; Read link, with completion for stored links.
  9238. (org-link-fontify-links-to-this-file)
  9239. (org-switch-to-buffer-other-window "*Org Links*")
  9240. (with-current-buffer "*Org Links*"
  9241. (erase-buffer)
  9242. (insert "Insert a link.
  9243. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9244. (when org-stored-links
  9245. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9246. (insert (mapconcat 'org-link-prettify
  9247. (reverse org-stored-links) "\n")))
  9248. (goto-char (point-min)))
  9249. (let ((cw (selected-window)))
  9250. (select-window (get-buffer-window "*Org Links*" 'visible))
  9251. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9252. (unless (pos-visible-in-window-p (point-max))
  9253. (org-fit-window-to-buffer))
  9254. (and (window-live-p cw) (select-window cw)))
  9255. ;; Fake a link history, containing the stored links.
  9256. (setq tmphist (append (mapcar 'car org-stored-links)
  9257. org-insert-link-history))
  9258. (setq all-prefixes (append (mapcar 'car abbrevs)
  9259. (mapcar 'car org-link-abbrev-alist)
  9260. org-link-types))
  9261. (unwind-protect
  9262. (progn
  9263. (setq link
  9264. (org-completing-read
  9265. "Link: "
  9266. (append
  9267. (mapcar (lambda (x) (concat x ":"))
  9268. all-prefixes)
  9269. (mapcar 'car org-stored-links))
  9270. nil nil nil
  9271. 'tmphist
  9272. (caar org-stored-links)))
  9273. (unless (string-match "\\S-" link)
  9274. (user-error "No link selected"))
  9275. (mapc (lambda(l)
  9276. (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
  9277. org-stored-links)
  9278. (when (or (member link all-prefixes)
  9279. (and (equal ":" (substring link -1))
  9280. (member (substring link 0 -1) all-prefixes)
  9281. (setq link (substring link 0 -1))))
  9282. (setq link (with-current-buffer origbuf
  9283. (org-link-try-special-completion link)))))
  9284. (set-window-configuration wcf)
  9285. (kill-buffer "*Org Links*"))
  9286. (setq entry (assoc link org-stored-links))
  9287. (or entry (push link org-insert-link-history))
  9288. (setq desc (or desc (nth 1 entry)))))
  9289. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9290. (not org-keep-stored-link-after-insertion))
  9291. (setq org-stored-links (delq (assoc link org-stored-links)
  9292. org-stored-links)))
  9293. (when (and (string-match org-plain-link-re link)
  9294. (not (string-match org-ts-regexp link)))
  9295. ;; URL-like link, normalize the use of angular brackets.
  9296. (setq link (org-remove-angle-brackets link)))
  9297. ;; Check if we are linking to the current file with a search
  9298. ;; option If yes, simplify the link by using only the search
  9299. ;; option.
  9300. (when (and buffer-file-name
  9301. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9302. (let* ((path (match-string 1 link))
  9303. (case-fold-search nil)
  9304. (search (match-string 2 link)))
  9305. (save-match-data
  9306. (when (equal (file-truename buffer-file-name) (file-truename path))
  9307. ;; We are linking to this same file, with a search option
  9308. (setq link search)))))
  9309. ;; Check if we can/should use a relative path. If yes, simplify the link
  9310. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9311. (let* ((type (match-string 1 link))
  9312. (path (match-string 2 link))
  9313. (origpath path)
  9314. (case-fold-search nil))
  9315. (cond
  9316. ((or (eq org-link-file-path-type 'absolute)
  9317. (equal complete-file '(16)))
  9318. (setq path (abbreviate-file-name (expand-file-name path))))
  9319. ((eq org-link-file-path-type 'noabbrev)
  9320. (setq path (expand-file-name path)))
  9321. ((eq org-link-file-path-type 'relative)
  9322. (setq path (file-relative-name path)))
  9323. (t
  9324. (save-match-data
  9325. (if (string-match (concat "^" (regexp-quote
  9326. (expand-file-name
  9327. (file-name-as-directory
  9328. default-directory))))
  9329. (expand-file-name path))
  9330. ;; We are linking a file with relative path name.
  9331. (setq path (substring (expand-file-name path)
  9332. (match-end 0)))
  9333. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9334. (setq link (concat type path))
  9335. (when (equal desc origpath)
  9336. (setq desc path))))
  9337. (if org-make-link-description-function
  9338. (setq desc
  9339. (or (condition-case nil
  9340. (funcall org-make-link-description-function link desc)
  9341. (error (progn (message "Can't get link description from `%s'"
  9342. (symbol-name org-make-link-description-function))
  9343. (sit-for 2) nil)))
  9344. (read-string "Description: " default-description)))
  9345. (if default-description (setq desc default-description)
  9346. (setq desc (or (and auto-desc desc)
  9347. (read-string "Description: " desc)))))
  9348. (unless (string-match "\\S-" desc) (setq desc nil))
  9349. (when remove (apply 'delete-region remove))
  9350. (insert (org-make-link-string link desc))
  9351. ;; Redisplay so as the new link has proper invisible characters.
  9352. (sit-for 0)))
  9353. (defun org-link-try-special-completion (type)
  9354. "If there is completion support for link type TYPE, offer it."
  9355. (let ((fun (intern (concat "org-" type "-complete-link"))))
  9356. (if (functionp fun)
  9357. (funcall fun)
  9358. (read-string "Link (no completion support): " (concat type ":")))))
  9359. (defun org-file-complete-link (&optional arg)
  9360. "Create a file link using completion."
  9361. (let ((file (org-iread-file-name "File: "))
  9362. (pwd (file-name-as-directory (expand-file-name ".")))
  9363. (pwd1 (file-name-as-directory (abbreviate-file-name
  9364. (expand-file-name ".")))))
  9365. (cond ((equal arg '(16))
  9366. (concat "file:"
  9367. (abbreviate-file-name (expand-file-name file))))
  9368. ((string-match
  9369. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9370. (concat "file:" (match-string 1 file)))
  9371. ((string-match
  9372. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9373. (expand-file-name file))
  9374. (concat "file:"
  9375. (match-string 1 (expand-file-name file))))
  9376. (t (concat "file:" file)))))
  9377. (defun org-iread-file-name (&rest args)
  9378. "Read-file-name using `ido-mode' speedup if available.
  9379. ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
  9380. See `read-file-name' for a description of parameters."
  9381. (org-without-partial-completion
  9382. (if (and org-completion-use-ido
  9383. (fboundp 'ido-read-file-name)
  9384. (org-bound-and-true-p ido-mode)
  9385. (listp (nth 1 args)))
  9386. (let ((ido-enter-matching-directory nil))
  9387. (apply #'ido-read-file-name args))
  9388. (apply #'read-file-name args))))
  9389. (defun org-completing-read (&rest args)
  9390. "Completing-read with SPACE being a normal character."
  9391. (let ((enable-recursive-minibuffers t)
  9392. (minibuffer-local-completion-map
  9393. (copy-keymap minibuffer-local-completion-map)))
  9394. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9395. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9396. (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
  9397. (apply 'org-icompleting-read args)))
  9398. (defun org-completing-read-no-i (&rest args)
  9399. (let (org-completion-use-ido org-completion-use-iswitchb)
  9400. (apply 'org-completing-read args)))
  9401. (defun org-iswitchb-completing-read (prompt choices &rest args)
  9402. "Use iswitch as a completing-read replacement to choose from choices.
  9403. PROMPT is a string to prompt with. CHOICES is a list of strings to choose
  9404. from."
  9405. (let* ((iswitchb-use-virtual-buffers nil)
  9406. (iswitchb-make-buflist-hook
  9407. (lambda ()
  9408. (setq iswitchb-temp-buflist choices))))
  9409. (iswitchb-read-buffer prompt)))
  9410. (defun org-icompleting-read (&rest args)
  9411. "Completing-read using `ido-mode' or `iswitchb' speedups if available.
  9412. Should be called like `completing-read'."
  9413. (org-without-partial-completion
  9414. (if (not (listp (nth 1 args)))
  9415. ;; Ido only supports lists as the COLLECTION argument. Use
  9416. ;; default completion function when second argument is not
  9417. ;; a list.
  9418. (apply #'completing-read args)
  9419. (let ((ido-enter-matching-directory nil))
  9420. (apply (cond ((and org-completion-use-ido
  9421. (fboundp 'ido-completing-read)
  9422. (org-bound-and-true-p ido-mode))
  9423. #'ido-completing-read)
  9424. ((and org-completion-use-iswitchb
  9425. (org-bound-and-true-p iswitchb-mode))
  9426. #'org-iswitchb-completing-read)
  9427. (t #'completing-read))
  9428. args)))))
  9429. ;;; Opening/following a link
  9430. (defvar org-link-search-failed nil)
  9431. (defvar org-open-link-functions nil
  9432. "Hook for functions finding a plain text link.
  9433. These functions must take a single argument, the link content.
  9434. They will be called for links that look like [[link text][description]]
  9435. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9436. like a filename (e.g. \"./blue.png\").
  9437. These functions will be called *before* Org attempts to resolve the
  9438. link by doing text searches in the current buffer - so if you want a
  9439. link \"[[target]]\" to still find \"<<target>>\", your function should
  9440. handle this as a special case.
  9441. When the function does handle the link, it must return a non-nil value.
  9442. If it decides that it is not responsible for this link, it must return
  9443. nil to indicate that that Org-mode can continue with other options
  9444. like exact and fuzzy text search.")
  9445. (defun org-next-link (&optional search-backward)
  9446. "Move forward to the next link.
  9447. If the link is in hidden text, expose it."
  9448. (interactive "P")
  9449. (when (and org-link-search-failed (eq this-command last-command))
  9450. (goto-char (point-min))
  9451. (message "Link search wrapped back to beginning of buffer"))
  9452. (setq org-link-search-failed nil)
  9453. (let* ((pos (point))
  9454. (ct (org-context))
  9455. (a (assoc :link ct))
  9456. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9457. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9458. ((looking-at org-any-link-re)
  9459. ;; Don't stay stuck at link without an org-link face
  9460. (forward-char (if search-backward -1 1))))
  9461. (if (funcall srch-fun org-any-link-re nil t)
  9462. (progn
  9463. (goto-char (match-beginning 0))
  9464. (when (outline-invisible-p) (org-show-context)))
  9465. (goto-char pos)
  9466. (setq org-link-search-failed t)
  9467. (message "No further link found"))))
  9468. (defun org-previous-link ()
  9469. "Move backward to the previous link.
  9470. If the link is in hidden text, expose it."
  9471. (interactive)
  9472. (funcall 'org-next-link t))
  9473. (defun org-translate-link (s)
  9474. "Translate a link string if a translation function has been defined."
  9475. (with-temp-buffer
  9476. (insert (org-trim s))
  9477. (org-trim (org-element-interpret-data (org-element-context)))))
  9478. (defun org-translate-link-from-planner (type path)
  9479. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9480. This is still an experimental function, your mileage may vary."
  9481. (cond
  9482. ((member type '("http" "https" "news" "ftp"))
  9483. ;; standard Internet links are the same.
  9484. nil)
  9485. ((and (equal type "irc") (string-match "^//" path))
  9486. ;; Planner has two / at the beginning of an irc link, we have 1.
  9487. ;; We should have zero, actually....
  9488. (setq path (substring path 1)))
  9489. ((and (equal type "lisp") (string-match "^/" path))
  9490. ;; Planner has a slash, we do not.
  9491. (setq type "elisp" path (substring path 1)))
  9492. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9493. ;; A typical message link. Planner has the id after the final slash,
  9494. ;; we separate it with a hash mark
  9495. (setq path (concat (match-string 1 path) "#"
  9496. (org-remove-angle-brackets (match-string 2 path))))))
  9497. (cons type path))
  9498. (defun org-find-file-at-mouse (ev)
  9499. "Open file link or URL at mouse."
  9500. (interactive "e")
  9501. (mouse-set-point ev)
  9502. (org-open-at-point 'in-emacs))
  9503. (defun org-open-at-mouse (ev)
  9504. "Open file link or URL at mouse.
  9505. See the docstring of `org-open-file' for details."
  9506. (interactive "e")
  9507. (mouse-set-point ev)
  9508. (when (eq major-mode 'org-agenda-mode)
  9509. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9510. (org-open-at-point))
  9511. (defvar org-window-config-before-follow-link nil
  9512. "The window configuration before following a link.
  9513. This is saved in case the need arises to restore it.")
  9514. ;;;###autoload
  9515. (defun org-open-at-point-global ()
  9516. "Follow a link like Org-mode does.
  9517. This command can be called in any mode to follow a link that has
  9518. Org-mode syntax."
  9519. (interactive)
  9520. (org-run-like-in-org-mode 'org-open-at-point))
  9521. ;;;###autoload
  9522. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9523. "Open a link in the string S, as if it was in Org-mode."
  9524. (interactive "sLink: \nP")
  9525. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9526. (with-temp-buffer
  9527. (let ((org-inhibit-startup (not reference-buffer)))
  9528. (org-mode)
  9529. (insert s)
  9530. (goto-char (point-min))
  9531. (when reference-buffer
  9532. (setq org-link-abbrev-alist-local
  9533. (with-current-buffer reference-buffer
  9534. org-link-abbrev-alist-local)))
  9535. (org-open-at-point arg reference-buffer)))))
  9536. (defvar org-open-at-point-functions nil
  9537. "Hook that is run when following a link at point.
  9538. Functions in this hook must return t if they identify and follow
  9539. a link at point. If they don't find anything interesting at point,
  9540. they must return nil.")
  9541. (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
  9542. (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
  9543. (defun org-open-at-point (&optional arg reference-buffer)
  9544. "Open link, timestamp, footnote or tags at point.
  9545. When point is on a link, follow it. Normally, files will be
  9546. opened by an appropriate application. If the optional prefix
  9547. argument ARG is non-nil, Emacs will visit the file. With
  9548. a double prefix argument, try to open outside of Emacs, in the
  9549. application the system uses for this file type.
  9550. When point is on a timestamp, open the agenda at the day
  9551. specified.
  9552. When point is a footnote definition, move to the first reference
  9553. found. If it is on a reference, move to the associated
  9554. definition.
  9555. When point is on a headline, display a list of every link in the
  9556. entry, so it is possible to pick one, or all, of them. If point
  9557. is on a tag, call `org-tags-view' instead.
  9558. When optional argument REFERENCE-BUFFER is non-nil, it should
  9559. specify a buffer from where the link search should happen. This
  9560. is used internally by `org-open-link-from-string'.
  9561. On top of syntactically correct links, this function will open
  9562. the link at point in comments or comment blocks and the first
  9563. link in a property drawer line."
  9564. (interactive "P")
  9565. ;; On a code block, open block's results.
  9566. (unless (call-interactively 'org-babel-open-src-block-result)
  9567. (org-load-modules-maybe)
  9568. (setq org-window-config-before-follow-link (current-window-configuration))
  9569. (org-remove-occur-highlights nil nil t)
  9570. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9571. (let* ((context
  9572. ;; Only consider supported types, even if they are not
  9573. ;; the closest one.
  9574. (org-element-lineage
  9575. (org-element-context)
  9576. '(clock comment comment-block footnote-definition
  9577. footnote-reference headline inlinetask keyword link
  9578. node-property timestamp)
  9579. t))
  9580. (type (org-element-type context))
  9581. (value (org-element-property :value context)))
  9582. (cond
  9583. ((not context) (user-error "No link found"))
  9584. ;; Exception: open timestamps and links in properties
  9585. ;; drawers, keywords and comments.
  9586. ((memq type '(comment comment-block keyword node-property))
  9587. (cond ((org-in-regexp org-any-link-re)
  9588. (org-open-link-from-string (match-string-no-properties 0)))
  9589. ((or (org-in-regexp org-ts-regexp-both nil t)
  9590. (org-in-regexp org-tsr-regexp-both nil t))
  9591. (org-follow-timestamp-link))
  9592. (t (user-error "No link found"))))
  9593. ;; On a headline or an inlinetask, but not on a timestamp,
  9594. ;; a link, a footnote reference or on tags.
  9595. ((and (memq type '(headline inlinetask))
  9596. ;; Not on tags.
  9597. (progn (save-excursion (beginning-of-line)
  9598. (looking-at org-complex-heading-regexp))
  9599. (or (not (match-beginning 5))
  9600. (< (point) (match-beginning 5)))))
  9601. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9602. (links (car data))
  9603. (links-end (cdr data)))
  9604. (if links
  9605. (dolist (link (if (stringp links) (list links) links))
  9606. (search-forward link nil links-end)
  9607. (goto-char (match-beginning 0))
  9608. (org-open-at-point))
  9609. (require 'org-attach)
  9610. (org-attach-reveal 'if-exists))))
  9611. ;; On a clock line, make sure point is on the timestamp
  9612. ;; before opening it.
  9613. ((and (eq type 'clock)
  9614. value
  9615. (>= (point) (org-element-property :begin value))
  9616. (<= (point) (org-element-property :end value)))
  9617. (org-follow-timestamp-link))
  9618. ;; Do nothing on white spaces after an object.
  9619. ((>= (point)
  9620. (save-excursion
  9621. (goto-char (org-element-property :end context))
  9622. (skip-chars-backward " \t")
  9623. (point)))
  9624. (user-error "No link found"))
  9625. ((eq type 'timestamp) (org-follow-timestamp-link))
  9626. ;; On tags within a headline or an inlinetask.
  9627. ((and (memq type '(headline inlinetask))
  9628. (progn (save-excursion (beginning-of-line)
  9629. (looking-at org-complex-heading-regexp))
  9630. (and (match-beginning 5)
  9631. (>= (point) (match-beginning 5)))))
  9632. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9633. ((eq type 'link)
  9634. ;; When link is located within the description of another
  9635. ;; link (e.g., an inline image), always open the parent
  9636. ;; link.
  9637. (let*((link (let ((up (org-element-property :parent context)))
  9638. (if (eq (org-element-type up) 'link) up context)))
  9639. (type (org-element-property :type link))
  9640. (path (org-link-unescape (org-element-property :path link))))
  9641. ;; Switch back to REFERENCE-BUFFER needed when called in
  9642. ;; a temporary buffer through `org-open-link-from-string'.
  9643. (with-current-buffer (or reference-buffer (current-buffer))
  9644. (cond
  9645. ((equal type "file")
  9646. (if (string-match "[*?{]" (file-name-nondirectory path))
  9647. (dired path)
  9648. ;; Look into `org-link-protocols' in order to find
  9649. ;; a DEDICATED-FUNCTION to open file. The function
  9650. ;; will be applied on raw link instead of parsed
  9651. ;; link due to the limitation in `org-add-link-type'
  9652. ;; ("open" function called with a single argument).
  9653. ;; If no such function is found, fallback to
  9654. ;; `org-open-file'.
  9655. ;;
  9656. ;; Note : "file+emacs" and "file+sys" types are
  9657. ;; hard-coded in order to escape the previous
  9658. ;; limitation.
  9659. (let* ((option (org-element-property :search-option link))
  9660. (app (org-element-property :application link))
  9661. (dedicated-function
  9662. (nth 1 (assoc app org-link-protocols))))
  9663. (if dedicated-function
  9664. (funcall dedicated-function
  9665. (concat path
  9666. (and option (concat "::" option))))
  9667. (apply #'org-open-file
  9668. path
  9669. (cond (arg)
  9670. ((equal app "emacs") 'emacs)
  9671. ((equal app "sys") 'system))
  9672. (cond ((not option) nil)
  9673. ((org-string-match-p "\\`[0-9]+\\'" option)
  9674. (list (string-to-number option)))
  9675. (t (list nil
  9676. (org-link-unescape option)))))))))
  9677. ((assoc type org-link-protocols)
  9678. (funcall (nth 1 (assoc type org-link-protocols)) path))
  9679. ((equal type "help")
  9680. (let ((f-or-v (intern path)))
  9681. (cond ((fboundp f-or-v) (describe-function f-or-v))
  9682. ((boundp f-or-v) (describe-variable f-or-v))
  9683. (t (error "Not a known function or variable")))))
  9684. ((member type '("http" "https" "ftp" "mailto" "news"))
  9685. (browse-url (org-link-escape-browser (concat type ":" path))))
  9686. ((equal type "doi")
  9687. (browse-url
  9688. (org-link-escape-browser (concat org-doi-server-url path))))
  9689. ((equal type "message") (browse-url (concat type ":" path)))
  9690. ((equal type "shell")
  9691. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9692. (cmd path))
  9693. (if (or (and (org-string-nw-p
  9694. org-confirm-shell-link-not-regexp)
  9695. (string-match
  9696. org-confirm-shell-link-not-regexp cmd))
  9697. (not org-confirm-shell-link-function)
  9698. (funcall org-confirm-shell-link-function
  9699. (format "Execute \"%s\" in shell? "
  9700. (org-add-props cmd nil
  9701. 'face 'org-warning))))
  9702. (progn
  9703. (message "Executing %s" cmd)
  9704. (shell-command cmd buf)
  9705. (when (featurep 'midnight)
  9706. (setq clean-buffer-list-kill-buffer-names
  9707. (cons (buffer-name buf)
  9708. clean-buffer-list-kill-buffer-names))))
  9709. (user-error "Abort"))))
  9710. ((equal type "elisp")
  9711. (let ((cmd path))
  9712. (if (or (and (org-string-nw-p
  9713. org-confirm-elisp-link-not-regexp)
  9714. (org-string-match-p
  9715. org-confirm-elisp-link-not-regexp cmd))
  9716. (not org-confirm-elisp-link-function)
  9717. (funcall org-confirm-elisp-link-function
  9718. (format "Execute \"%s\" as elisp? "
  9719. (org-add-props cmd nil
  9720. 'face 'org-warning))))
  9721. (message "%s => %s" cmd
  9722. (if (eq (string-to-char cmd) ?\()
  9723. (eval (read cmd))
  9724. (call-interactively (read cmd))))
  9725. (user-error "Abort"))))
  9726. ((equal type "id")
  9727. (require 'org-id)
  9728. (funcall (nth 1 (assoc "id" org-link-protocols)) path))
  9729. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9730. (unless (run-hook-with-args-until-success
  9731. 'org-open-link-functions path)
  9732. (if (not arg) (org-mark-ring-push)
  9733. (switch-to-buffer-other-window
  9734. (org-get-buffer-for-internal-link (current-buffer))))
  9735. (let ((destination
  9736. (org-with-wide-buffer
  9737. (if (equal type "radio")
  9738. (org-search-radio-target
  9739. (org-element-property :path link))
  9740. (org-link-search
  9741. (if (member type '("custom-id" "coderef"))
  9742. (org-element-property :raw-link link)
  9743. path)
  9744. ;; Prevent fuzzy links from matching
  9745. ;; themselves.
  9746. (and (equal type "fuzzy")
  9747. (+ 2 (org-element-property :begin link)))))
  9748. (point))))
  9749. (unless (and (<= (point-min) destination)
  9750. (>= (point-max) destination))
  9751. (widen))
  9752. (goto-char destination))))
  9753. (t (browse-url-at-point))))))
  9754. ;; On a footnote reference or at a footnote definition's label.
  9755. ((or (eq type 'footnote-reference)
  9756. (and (eq type 'footnote-definition)
  9757. (save-excursion
  9758. ;; Do not validate action when point is on the
  9759. ;; spaces right after the footnote label, in
  9760. ;; order to be on par with behaviour on links.
  9761. (skip-chars-forward " \t")
  9762. (let ((begin
  9763. (org-element-property :contents-begin context)))
  9764. (if begin (< (point) begin)
  9765. (= (org-element-property :post-affiliated context)
  9766. (line-beginning-position)))))))
  9767. (org-footnote-action))
  9768. (t (user-error "No link found")))))
  9769. (run-hook-with-args 'org-follow-link-hook)))
  9770. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9771. "Offer links in the current entry and return the selected link.
  9772. If there is only one link, return it.
  9773. If NTH is an integer, return the NTH link found.
  9774. If ZERO is a string, check also this string for a link, and if
  9775. there is one, return it."
  9776. (with-current-buffer buffer
  9777. (save-excursion
  9778. (save-restriction
  9779. (widen)
  9780. (goto-char marker)
  9781. (let ((cnt ?0)
  9782. (in-emacs (unless (integerp nth) nth))
  9783. have-zero end links link c)
  9784. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9785. (push (match-string 0 zero) links)
  9786. (setq cnt (1- cnt) have-zero t))
  9787. (save-excursion
  9788. (org-back-to-heading t)
  9789. (setq end (save-excursion (outline-next-heading) (point)))
  9790. (while (re-search-forward org-any-link-re end t)
  9791. (push (match-string 0) links))
  9792. (setq links (org-uniquify (reverse links))))
  9793. (cond
  9794. ((null links)
  9795. (message "No links"))
  9796. ((equal (length links) 1)
  9797. (setq link (car links)))
  9798. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9799. (setq link (nth (if have-zero nth (1- nth)) links)))
  9800. (t ; we have to select a link
  9801. (save-excursion
  9802. (save-window-excursion
  9803. (delete-other-windows)
  9804. (with-output-to-temp-buffer "*Select Link*"
  9805. (mapc (lambda (l)
  9806. (if (not (string-match org-bracket-link-regexp l))
  9807. (princ (format "[%c] %s\n" (incf cnt)
  9808. (org-remove-angle-brackets l)))
  9809. (if (match-end 3)
  9810. (princ (format "[%c] %s (%s)\n" (incf cnt)
  9811. (match-string 3 l) (match-string 1 l)))
  9812. (princ (format "[%c] %s\n" (incf cnt)
  9813. (match-string 1 l))))))
  9814. links))
  9815. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9816. (message "Select link to open, RET to open all:")
  9817. (setq c (read-char-exclusive))
  9818. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9819. (when (equal c ?q) (user-error "Abort"))
  9820. (if (equal c ?\C-m)
  9821. (setq link links)
  9822. (setq nth (- c ?0))
  9823. (when have-zero (setq nth (1+ nth)))
  9824. (unless (and (integerp nth) (>= (length links) nth))
  9825. (user-error "Invalid link selection"))
  9826. (setq link (nth (1- nth) links)))))
  9827. (cons link end))))))
  9828. ;; TODO: These functions are deprecated since `org-open-at-point'
  9829. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9830. (defun org-open-file-with-system (path)
  9831. "Open file at PATH using the system way of opening it."
  9832. (org-open-file path 'system))
  9833. (defun org-open-file-with-emacs (path)
  9834. "Open file at PATH in Emacs."
  9835. (org-open-file path 'emacs))
  9836. ;;; File search
  9837. (defvar org-create-file-search-functions nil
  9838. "List of functions to construct the right search string for a file link.
  9839. These functions are called in turn with point at the location to
  9840. which the link should point.
  9841. A function in the hook should first test if it would like to
  9842. handle this file type, for example by checking the `major-mode'
  9843. or the file extension. If it decides not to handle this file, it
  9844. should just return nil to give other functions a chance. If it
  9845. does handle the file, it must return the search string to be used
  9846. when following the link. The search string will be part of the
  9847. file link, given after a double colon, and `org-open-at-point'
  9848. will automatically search for it. If special measures must be
  9849. taken to make the search successful, another function should be
  9850. added to the companion hook `org-execute-file-search-functions',
  9851. which see.
  9852. A function in this hook may also use `setq' to set the variable
  9853. `description' to provide a suggestion for the descriptive text to
  9854. be used for this link when it gets inserted into an Org-mode
  9855. buffer with \\[org-insert-link].")
  9856. (defvar org-execute-file-search-functions nil
  9857. "List of functions to execute a file search triggered by a link.
  9858. Functions added to this hook must accept a single argument, the
  9859. search string that was part of the file link, the part after the
  9860. double colon. The function must first check if it would like to
  9861. handle this search, for example by checking the `major-mode' or
  9862. the file extension. If it decides not to handle this search, it
  9863. should just return nil to give other functions a chance. If it
  9864. does handle the search, it must return a non-nil value to keep
  9865. other functions from trying.
  9866. Each function can access the current prefix argument through the
  9867. variable `current-prefix-arg'. Note that a single prefix is used
  9868. to force opening a link in Emacs, so it may be good to only use a
  9869. numeric or double prefix to guide the search function.
  9870. In case this is needed, a function in this hook can also restore
  9871. the window configuration before `org-open-at-point' was called using:
  9872. (set-window-configuration org-window-config-before-follow-link)")
  9873. (defun org-search-radio-target (target)
  9874. "Search a radio target matching TARGET in current buffer.
  9875. White spaces are not significant."
  9876. (let ((re (format "<<<%s>>>"
  9877. (mapconcat #'regexp-quote
  9878. (org-split-string target "[ \t\n]+")
  9879. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9880. (origin (point)))
  9881. (goto-char (point-min))
  9882. (catch :radio-match
  9883. (while (re-search-forward re nil t)
  9884. (backward-char)
  9885. (let ((object (org-element-context)))
  9886. (when (eq (org-element-type object) 'radio-target)
  9887. (goto-char (org-element-property :begin object))
  9888. (org-show-context 'link-search)
  9889. (throw :radio-match nil))))
  9890. (goto-char origin)
  9891. (user-error "No match for radio target: %s" target))))
  9892. (defun org-link-search (s &optional avoid-pos stealth)
  9893. "Search for a search string S.
  9894. If S starts with \"#\", it triggers a custom ID search.
  9895. If S is enclosed within parenthesis, it initiates a coderef
  9896. search.
  9897. If S is surrounded by forward slashes, it is interpreted as
  9898. a regular expression. In Org mode files, this will create an
  9899. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9900. to list matches. If the current buffer is in `dired-mode', grep
  9901. will be used to search in all files.
  9902. When AVOID-POS is given, ignore matches near that position.
  9903. When optional argument STEALTH is non-nil, do not modify
  9904. visibility around point, thus ignoring `org-show-context-detail'
  9905. variable.
  9906. Search is case-insensitive and ignores white spaces. Return type
  9907. of matched result, with is either `dedicated' or `fuzzy'."
  9908. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9909. (let* ((case-fold-search t)
  9910. (origin (point))
  9911. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9912. (words (org-split-string s "[ \t\n]+"))
  9913. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  9914. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9915. type)
  9916. (cond
  9917. ;; Check if there are any special search functions.
  9918. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9919. ((eq (string-to-char s) ?#)
  9920. ;; Look for a custom ID S if S starts with "#".
  9921. (let* ((id (substring normalized 1))
  9922. (match (org-find-property "CUSTOM_ID" id)))
  9923. (if match (progn (goto-char match) (setf type 'dedicated))
  9924. (error "No match for custom ID: %s" id))))
  9925. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9926. ;; Look for coderef targets if S is enclosed within parenthesis.
  9927. (let ((coderef (match-string-no-properties 1 normalized))
  9928. (re (substring s-single-re 1 -1)))
  9929. (goto-char (point-min))
  9930. (catch :coderef-match
  9931. (while (re-search-forward re nil t)
  9932. (let ((element (org-element-at-point)))
  9933. (when (and (memq (org-element-type element)
  9934. '(example-block src-block))
  9935. ;; Build proper regexp according to current
  9936. ;; block's label format.
  9937. (let ((label-fmt
  9938. (regexp-quote
  9939. (or (org-element-property :label-fmt element)
  9940. org-coderef-label-format))))
  9941. (save-excursion
  9942. (beginning-of-line)
  9943. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9944. (format label-fmt coderef))))))
  9945. (setq type 'dedicated)
  9946. (goto-char (match-beginning 1))
  9947. (throw :coderef-match nil))))
  9948. (goto-char origin)
  9949. (error "No match for coderef: %s" coderef))))
  9950. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9951. ;; Look for a regular expression.
  9952. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9953. (match-string 1 s)))
  9954. ;; Fuzzy links.
  9955. (t
  9956. (let* ((starred (eq (string-to-char normalized) ?*))
  9957. (headline-search (and (derived-mode-p 'org-mode)
  9958. (or org-link-search-must-match-exact-headline
  9959. starred))))
  9960. (cond
  9961. ;; Look for targets, only if not in a headline search.
  9962. ((and (not starred)
  9963. (let ((target (format "<<%s>>" s-multi-re)))
  9964. (catch :target-match
  9965. (goto-char (point-min))
  9966. (while (re-search-forward target nil t)
  9967. (backward-char)
  9968. (let ((context (org-element-context)))
  9969. (when (eq (org-element-type context) 'target)
  9970. (setq type 'dedicated)
  9971. (goto-char (org-element-property :begin context))
  9972. (throw :target-match t))))
  9973. nil))))
  9974. ;; Look for elements named after S, only if not in a headline
  9975. ;; search.
  9976. ((and (not starred)
  9977. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9978. (catch :name-match
  9979. (goto-char (point-min))
  9980. (while (re-search-forward name nil t)
  9981. (let ((element (org-element-at-point)))
  9982. (when (equal (org-split-string
  9983. (org-element-property :name element)
  9984. "[ \t]+")
  9985. words)
  9986. (setq type 'dedicated)
  9987. (beginning-of-line)
  9988. (throw :name-match t))))
  9989. nil))))
  9990. ;; Regular text search. Prefer headlines in Org mode
  9991. ;; buffers.
  9992. ((and (derived-mode-p 'org-mode)
  9993. (let* ((wspace "[ \t]")
  9994. (wspaceopt (concat wspace "*"))
  9995. (cookie (concat "\\(?:"
  9996. wspaceopt
  9997. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
  9998. wspaceopt
  9999. "\\)"))
  10000. (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
  10001. (re (concat
  10002. org-outline-regexp-bol
  10003. "\\(?:" org-todo-regexp "[ \t]+\\)?"
  10004. "\\(?:\\[#.\\][ \t]+\\)?"
  10005. "\\(?:" org-comment-string "[ \t]+\\)?"
  10006. sep "?"
  10007. (let ((title (mapconcat #'regexp-quote
  10008. words
  10009. sep)))
  10010. (if starred (substring title 1) title))
  10011. sep "?"
  10012. (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
  10013. "[ \t]*$")))
  10014. (goto-char (point-min))
  10015. (re-search-forward re nil t)))
  10016. (goto-char (match-beginning 0))
  10017. (setq type 'dedicated))
  10018. ;; Offer to create non-existent headline depending on
  10019. ;; `org-link-search-must-match-exact-headline'.
  10020. ((and (derived-mode-p 'org-mode)
  10021. (not org-link-search-inhibit-query)
  10022. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10023. (yes-or-no-p "No match - create this as a new heading? "))
  10024. (goto-char (point-max))
  10025. (unless (bolp) (newline))
  10026. (org-insert-heading nil t t)
  10027. (insert s "\n")
  10028. (beginning-of-line 0))
  10029. ;; Only headlines are looked after. No need to process
  10030. ;; further: throw an error.
  10031. ((and (derived-mode-p 'org-mode)
  10032. (or starred org-link-search-must-match-exact-headline))
  10033. (goto-char origin)
  10034. (error "No match for fuzzy expression: %s" normalized))
  10035. ;; Regular text search.
  10036. ((catch :fuzzy-match
  10037. (goto-char (point-min))
  10038. (while (re-search-forward s-multi-re nil t)
  10039. ;; Skip match if it contains AVOID-POS or it is included
  10040. ;; in a link with a description but outside the
  10041. ;; description.
  10042. (unless (or (and avoid-pos
  10043. (<= (match-beginning 0) avoid-pos)
  10044. (> (match-end 0) avoid-pos))
  10045. (and (save-match-data
  10046. (org-in-regexp org-bracket-link-regexp))
  10047. (match-beginning 3)
  10048. (or (> (match-beginning 3) (point))
  10049. (<= (match-end 3) (point)))
  10050. (org-element-lineage
  10051. (save-match-data (org-element-context))
  10052. '(link) t)))
  10053. (goto-char (match-beginning 0))
  10054. (setq type 'fuzzy)
  10055. (throw :fuzzy-match t)))
  10056. nil))
  10057. ;; All failed. Throw an error.
  10058. (t (goto-char origin)
  10059. (error "No match for fuzzy expression: %s" normalized))))))
  10060. ;; Disclose surroundings of match, if appropriate.
  10061. (when (and (derived-mode-p 'org-mode) (not stealth))
  10062. (org-show-context 'link-search))
  10063. type))
  10064. (defun org-get-buffer-for-internal-link (buffer)
  10065. "Return a buffer to be used for displaying the link target of internal links."
  10066. (cond
  10067. ((not org-display-internal-link-with-indirect-buffer)
  10068. buffer)
  10069. ((string-match "(Clone)$" (buffer-name buffer))
  10070. (message "Buffer is already a clone, not making another one")
  10071. ;; we also do not modify visibility in this case
  10072. buffer)
  10073. (t ; make a new indirect buffer for displaying the link
  10074. (let* ((bn (buffer-name buffer))
  10075. (ibn (concat bn "(Clone)"))
  10076. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10077. (with-current-buffer ib (org-overview))
  10078. ib))))
  10079. (defun org-do-occur (regexp &optional cleanup)
  10080. "Call the Emacs command `occur'.
  10081. If CLEANUP is non-nil, remove the printout of the regular expression
  10082. in the *Occur* buffer. This is useful if the regex is long and not useful
  10083. to read."
  10084. (occur regexp)
  10085. (when cleanup
  10086. (let ((cwin (selected-window)) win beg end)
  10087. (when (setq win (get-buffer-window "*Occur*"))
  10088. (select-window win))
  10089. (goto-char (point-min))
  10090. (when (re-search-forward "match[a-z]+" nil t)
  10091. (setq beg (match-end 0))
  10092. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10093. (setq end (1- (match-beginning 0)))))
  10094. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10095. (goto-char (point-min))
  10096. (select-window cwin))))
  10097. ;;; The mark ring for links jumps
  10098. (defvar org-mark-ring nil
  10099. "Mark ring for positions before jumps in Org-mode.")
  10100. (defvar org-mark-ring-last-goto nil
  10101. "Last position in the mark ring used to go back.")
  10102. ;; Fill and close the ring
  10103. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10104. (loop for i from 1 to org-mark-ring-length do
  10105. (push (make-marker) org-mark-ring))
  10106. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10107. org-mark-ring)
  10108. (defun org-mark-ring-push (&optional pos buffer)
  10109. "Put the current position or POS into the mark ring and rotate it."
  10110. (interactive)
  10111. (setq pos (or pos (point)))
  10112. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10113. (move-marker (car org-mark-ring)
  10114. (or pos (point))
  10115. (or buffer (current-buffer)))
  10116. (message "%s"
  10117. (substitute-command-keys
  10118. "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
  10119. (defun org-mark-ring-goto (&optional n)
  10120. "Jump to the previous position in the mark ring.
  10121. With prefix arg N, jump back that many stored positions. When
  10122. called several times in succession, walk through the entire ring.
  10123. Org-mode commands jumping to a different position in the current file,
  10124. or to another Org-mode file, automatically push the old position
  10125. onto the ring."
  10126. (interactive "p")
  10127. (let (p m)
  10128. (if (eq last-command this-command)
  10129. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10130. (setq p org-mark-ring))
  10131. (setq org-mark-ring-last-goto p)
  10132. (setq m (car p))
  10133. (org-pop-to-buffer-same-window (marker-buffer m))
  10134. (goto-char m)
  10135. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10136. ;;; TODO: Use string-remove-prefix and -suffix once we only support
  10137. ;;; Emacs 24.4+
  10138. (defun org-remove-angle-brackets (s)
  10139. (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
  10140. (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
  10141. s)
  10142. (defun org-add-angle-brackets (s)
  10143. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10144. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10145. s)
  10146. (defun org-remove-double-quotes (s)
  10147. (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
  10148. (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
  10149. s)
  10150. ;;; Following specific links
  10151. (defun org-follow-timestamp-link ()
  10152. "Open an agenda view for the time-stamp date/range at point."
  10153. (cond
  10154. ((org-at-date-range-p t)
  10155. (let ((org-agenda-start-on-weekday)
  10156. (t1 (match-string 1))
  10157. (t2 (match-string 2)) tt1 tt2)
  10158. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10159. tt2 (time-to-days (org-time-string-to-time t2)))
  10160. (let ((org-agenda-buffer-tmp-name
  10161. (format "*Org Agenda(a:%s)"
  10162. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10163. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10164. ((org-at-timestamp-p t)
  10165. (let ((org-agenda-buffer-tmp-name
  10166. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10167. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10168. (substring (match-string 1) 0 10)))
  10169. 1)))
  10170. (t (error "This should not happen"))))
  10171. ;;; Following file links
  10172. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10173. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10174. (declare-function mailcap-mime-info
  10175. "mailcap" (string &optional request no-decode))
  10176. (defvar org-wait nil)
  10177. (defun org-open-file (path &optional in-emacs line search)
  10178. "Open the file at PATH.
  10179. First, this expands any special file name abbreviations. Then the
  10180. configuration variable `org-file-apps' is checked if it contains an
  10181. entry for this file type, and if yes, the corresponding command is launched.
  10182. If no application is found, Emacs simply visits the file.
  10183. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10184. With a double \\[universal-argument] \\[universal-argument] \
  10185. prefix arg, Org tries to avoid opening in Emacs
  10186. and to use an external application to visit the file.
  10187. Optional LINE specifies a line to go to, optional SEARCH a string
  10188. to search for. If LINE or SEARCH is given, the file will be
  10189. opened in Emacs, unless an entry from org-file-apps that makes
  10190. use of groups in a regexp matches.
  10191. If you want to change the way frames are used when following a
  10192. link, please customize `org-link-frame-setup'.
  10193. If the file does not exist, an error is thrown."
  10194. (let* ((file (if (equal path "")
  10195. buffer-file-name
  10196. (substitute-in-file-name (expand-file-name path))))
  10197. (file-apps (append org-file-apps (org-default-apps)))
  10198. (apps (cl-remove-if
  10199. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10200. (apps-dlink (cl-remove-if-not
  10201. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10202. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10203. (dirp (unless remp (file-directory-p file)))
  10204. (file (if (and dirp org-open-directory-means-index-dot-org)
  10205. (concat (file-name-as-directory file) "index.org")
  10206. file))
  10207. (a-m-a-p (assq 'auto-mode apps))
  10208. (dfile (downcase file))
  10209. ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
  10210. (link (cond ((and (eq line nil)
  10211. (eq search nil))
  10212. file)
  10213. (line
  10214. (concat file "::" (number-to-string line)))
  10215. (search
  10216. (concat file "::" search))))
  10217. (dlink (downcase link))
  10218. (old-buffer (current-buffer))
  10219. (old-pos (point))
  10220. (old-mode major-mode)
  10221. ext cmd link-match-data)
  10222. (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
  10223. (setq ext (match-string 1 dfile))
  10224. (when (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
  10225. (setq ext (match-string 1 dfile))))
  10226. (cond
  10227. ((member in-emacs '((16) system))
  10228. (setq cmd (cdr (assoc 'system apps))))
  10229. (in-emacs (setq cmd 'emacs))
  10230. (t
  10231. (setq cmd (or (and remp (cdr (assoc 'remote apps)))
  10232. (and dirp (cdr (assoc 'directory apps)))
  10233. ; first, try matching against apps-dlink
  10234. ; if we get a match here, store the match data for later
  10235. (let ((match (assoc-default dlink apps-dlink
  10236. 'string-match)))
  10237. (if match
  10238. (progn (setq link-match-data (match-data))
  10239. match)
  10240. (progn (setq in-emacs (or in-emacs line search))
  10241. nil))) ; if we have no match in apps-dlink,
  10242. ; always open the file in emacs if line or search
  10243. ; is given (for backwards compatibility)
  10244. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10245. 'string-match)
  10246. (cdr (assoc ext apps))
  10247. (cdr (assoc t apps))))))
  10248. (when (eq cmd 'system)
  10249. (setq cmd (cdr (assoc 'system apps))))
  10250. (when (eq cmd 'default)
  10251. (setq cmd (cdr (assoc t apps))))
  10252. (when (eq cmd 'mailcap)
  10253. (require 'mailcap)
  10254. (mailcap-parse-mailcaps)
  10255. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10256. (command (mailcap-mime-info mime-type)))
  10257. (if (stringp command)
  10258. (setq cmd command)
  10259. (setq cmd 'emacs))))
  10260. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10261. (not (file-exists-p file))
  10262. (not org-open-non-existing-files))
  10263. (user-error "No such file: %s" file))
  10264. (cond
  10265. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10266. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10267. (while (string-match "['\"]%s['\"]" cmd)
  10268. (setq cmd (replace-match "%s" t t cmd)))
  10269. (while (string-match "%s" cmd)
  10270. (setq cmd (replace-match
  10271. (save-match-data
  10272. (shell-quote-argument
  10273. (convert-standard-filename file)))
  10274. t t cmd)))
  10275. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10276. (save-match-data
  10277. (let ((match-index 1)
  10278. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10279. (set-match-data link-match-data)
  10280. (while (<= match-index number-of-groups)
  10281. (let ((regex (concat "%" (number-to-string match-index)))
  10282. (replace-with (match-string match-index dlink)))
  10283. (while (string-match regex cmd)
  10284. (setq cmd (replace-match replace-with t t cmd))))
  10285. (setq match-index (+ match-index 1)))))
  10286. (save-window-excursion
  10287. (message "Running %s...done" cmd)
  10288. (start-process-shell-command cmd nil cmd)
  10289. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10290. ((or (stringp cmd)
  10291. (eq cmd 'emacs))
  10292. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10293. (widen)
  10294. (if line (progn (org-goto-line line)
  10295. (when (derived-mode-p 'org-mode)
  10296. (org-reveal)))
  10297. (when search (org-link-search search))))
  10298. ((consp cmd)
  10299. (let ((file (convert-standard-filename file)))
  10300. (save-match-data
  10301. (set-match-data link-match-data)
  10302. (eval cmd))))
  10303. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10304. (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
  10305. (or (not (equal old-buffer (current-buffer)))
  10306. (not (equal old-pos (point))))
  10307. (org-mark-ring-push old-pos old-buffer))))
  10308. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10309. "This function returns non-nil if `entry' uses a regular
  10310. expression which should be matched against the whole link by
  10311. org-open-file.
  10312. It assumes that is the case when the entry uses a regular
  10313. expression which has at least one grouping construct and the
  10314. action is either a lisp form or a command string containing
  10315. `%1', i.e. using at least one subexpression match as a
  10316. parameter."
  10317. (let ((selector (car entry))
  10318. (action (cdr entry)))
  10319. (if (stringp selector)
  10320. (and (> (regexp-opt-depth selector) 0)
  10321. (or (and (stringp action)
  10322. (string-match "%[0-9]" action))
  10323. (consp action)))
  10324. nil)))
  10325. (defun org-default-apps ()
  10326. "Return the default applications for this operating system."
  10327. (cond
  10328. ((eq system-type 'darwin)
  10329. org-file-apps-defaults-macosx)
  10330. ((eq system-type 'windows-nt)
  10331. org-file-apps-defaults-windowsnt)
  10332. (t org-file-apps-defaults-gnu)))
  10333. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10334. "Convert extensions to regular expressions in the cars of LIST.
  10335. Also, weed out any non-string entries, because the return value is used
  10336. only for regexp matching.
  10337. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10338. point to the symbol `emacs', indicating that the file should
  10339. be opened in Emacs."
  10340. (append
  10341. (delq nil
  10342. (mapcar (lambda (x)
  10343. (unless (not (stringp (car x)))
  10344. (if (string-match "\\W" (car x))
  10345. x
  10346. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10347. list))
  10348. (when add-auto-mode
  10349. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10350. (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
  10351. (defun org-file-remote-p (file)
  10352. "Test whether FILE specifies a location on a remote system.
  10353. Return non-nil if the location is indeed remote.
  10354. For example, the filename \"/user@host:/foo\" specifies a location
  10355. on the system \"/user@host:\"."
  10356. (cond ((fboundp 'file-remote-p)
  10357. (file-remote-p file))
  10358. ((fboundp 'tramp-handle-file-remote-p)
  10359. (tramp-handle-file-remote-p file))
  10360. ((and (boundp 'ange-ftp-name-format)
  10361. (string-match (car ange-ftp-name-format) file))
  10362. t)))
  10363. ;;;; Refiling
  10364. (defun org-get-org-file ()
  10365. "Read a filename, with default directory `org-directory'."
  10366. (let ((default (or org-default-notes-file remember-data-file)))
  10367. (read-file-name (format "File name [%s]: " default)
  10368. (file-name-as-directory org-directory)
  10369. default)))
  10370. (defun org-notes-order-reversed-p ()
  10371. "Check if the current file should receive notes in reversed order."
  10372. (cond
  10373. ((not org-reverse-note-order) nil)
  10374. ((eq t org-reverse-note-order) t)
  10375. ((not (listp org-reverse-note-order)) nil)
  10376. (t (catch 'exit
  10377. (dolist (entry org-reverse-note-order)
  10378. (when (string-match (car entry) buffer-file-name)
  10379. (throw 'exit (cdr entry))))))))
  10380. (defvar org-refile-target-table nil
  10381. "The list of refile targets, created by `org-refile'.")
  10382. (defvar org-agenda-new-buffers nil
  10383. "Buffers created to visit agenda files.")
  10384. (defvar org-refile-cache nil
  10385. "Cache for refile targets.")
  10386. (defvar org-refile-markers nil
  10387. "All the markers used for caching refile locations.")
  10388. (defun org-refile-marker (pos)
  10389. "Get a new refile marker, but only if caching is in use."
  10390. (if (not org-refile-use-cache)
  10391. pos
  10392. (let ((m (make-marker)))
  10393. (move-marker m pos)
  10394. (push m org-refile-markers)
  10395. m)))
  10396. (defun org-refile-cache-clear ()
  10397. "Clear the refile cache and disable all the markers."
  10398. (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
  10399. (setq org-refile-markers nil)
  10400. (setq org-refile-cache nil)
  10401. (message "Refile cache has been cleared"))
  10402. (defun org-refile-cache-check-set (set)
  10403. "Check if all the markers in the cache still have live buffers."
  10404. (let (marker)
  10405. (catch 'exit
  10406. (while (and set (setq marker (nth 3 (pop set))))
  10407. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10408. (when (and marker (null (marker-buffer marker)))
  10409. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10410. (sit-for 3)
  10411. (throw 'exit nil)))
  10412. t)))
  10413. (defun org-refile-cache-put (set &rest identifiers)
  10414. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10415. (let* ((key (sha1 (prin1-to-string identifiers)))
  10416. (entry (assoc key org-refile-cache)))
  10417. (if entry
  10418. (setcdr entry set)
  10419. (push (cons key set) org-refile-cache))))
  10420. (defun org-refile-cache-get (&rest identifiers)
  10421. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10422. (cond
  10423. ((not org-refile-cache) nil)
  10424. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10425. (t
  10426. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10427. org-refile-cache))))
  10428. (and set (org-refile-cache-check-set set) set)))))
  10429. (defun org-refile-get-targets (&optional default-buffer excluded-entries)
  10430. "Produce a table with refile targets."
  10431. (let ((case-fold-search nil)
  10432. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10433. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10434. targets tgs txt re files desc descre fast-path-p level pos0)
  10435. (message "Getting targets...")
  10436. (with-current-buffer (or default-buffer (current-buffer))
  10437. (dolist (entry entries)
  10438. (setq files (car entry) desc (cdr entry))
  10439. (setq fast-path-p nil)
  10440. (cond
  10441. ((null files) (setq files (list (current-buffer))))
  10442. ((eq files 'org-agenda-files)
  10443. (setq files (org-agenda-files 'unrestricted)))
  10444. ((and (symbolp files) (fboundp files))
  10445. (setq files (funcall files)))
  10446. ((and (symbolp files) (boundp files))
  10447. (setq files (symbol-value files))))
  10448. (when (stringp files) (setq files (list files)))
  10449. (cond
  10450. ((eq (car desc) :tag)
  10451. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10452. ((eq (car desc) :todo)
  10453. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10454. ((eq (car desc) :regexp)
  10455. (setq descre (cdr desc)))
  10456. ((eq (car desc) :level)
  10457. (setq descre (concat "^\\*\\{" (number-to-string
  10458. (if org-odd-levels-only
  10459. (1- (* 2 (cdr desc)))
  10460. (cdr desc)))
  10461. "\\}[ \t]")))
  10462. ((eq (car desc) :maxlevel)
  10463. (setq fast-path-p t)
  10464. (setq descre (concat "^\\*\\{1," (number-to-string
  10465. (if org-odd-levels-only
  10466. (1- (* 2 (cdr desc)))
  10467. (cdr desc)))
  10468. "\\}[ \t]")))
  10469. (t (error "Bad refiling target description %s" desc)))
  10470. (dolist (f files)
  10471. (with-current-buffer
  10472. (if (bufferp f) f (org-get-agenda-file-buffer f))
  10473. (or
  10474. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10475. (progn
  10476. (when (bufferp f) (setq f (buffer-file-name
  10477. (buffer-base-buffer f))))
  10478. (setq f (and f (expand-file-name f)))
  10479. (when (eq org-refile-use-outline-path 'file)
  10480. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10481. (save-excursion
  10482. (save-restriction
  10483. (widen)
  10484. (goto-char (point-min))
  10485. (while (re-search-forward descre nil t)
  10486. (goto-char (setq pos0 (point-at-bol)))
  10487. (catch 'next
  10488. (when org-refile-target-verify-function
  10489. (save-match-data
  10490. (or (funcall org-refile-target-verify-function)
  10491. (throw 'next t))))
  10492. (when (and (looking-at org-complex-heading-regexp)
  10493. (not (member (match-string 4) excluded-entries))
  10494. (match-string 4))
  10495. (setq level (org-reduced-level
  10496. (- (match-end 1) (match-beginning 1)))
  10497. txt (org-link-display-format (match-string 4))
  10498. txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
  10499. re (format org-complex-heading-regexp-format
  10500. (regexp-quote (match-string 4))))
  10501. (when org-refile-use-outline-path
  10502. (setq txt (mapconcat
  10503. 'org-protect-slash
  10504. (append
  10505. (if (eq org-refile-use-outline-path
  10506. 'file)
  10507. (list (file-name-nondirectory
  10508. (buffer-file-name
  10509. (buffer-base-buffer))))
  10510. (when (eq org-refile-use-outline-path
  10511. 'full-file-path)
  10512. (list (buffer-file-name
  10513. (buffer-base-buffer)))))
  10514. (org-get-outline-path fast-path-p
  10515. level txt)
  10516. (list txt))
  10517. "/")))
  10518. (push (list txt f re (org-refile-marker (point)))
  10519. tgs)))
  10520. (when (= (point) pos0)
  10521. ;; verification function has not moved point
  10522. (goto-char (point-at-eol))))))))
  10523. (when org-refile-use-cache
  10524. (org-refile-cache-put tgs (buffer-file-name) descre))
  10525. (setq targets (append tgs targets))))))
  10526. (message "Getting targets...done")
  10527. (nreverse targets)))
  10528. (defun org-protect-slash (s)
  10529. (while (string-match "/" s)
  10530. (setq s (replace-match "\\" t t s)))
  10531. s)
  10532. (defvar org-olpa (make-vector 20 nil))
  10533. (defun org-get-outline-path (&optional fastp level heading)
  10534. "Return the outline path to the current entry, as a list.
  10535. The parameters FASTP, LEVEL, and HEADING are for use by a scanner
  10536. routine which makes outline path derivations for an entire file,
  10537. avoiding backtracing. Refile target collection makes use of that."
  10538. (if fastp
  10539. (progn
  10540. (when (> level 19)
  10541. (error "Outline path failure, more than 19 levels"))
  10542. (loop for i from level upto 19 do
  10543. (aset org-olpa i nil))
  10544. (prog1
  10545. (delq nil (append org-olpa nil))
  10546. (aset org-olpa level heading)))
  10547. (let (rtn case-fold-search)
  10548. (save-excursion
  10549. (save-restriction
  10550. (widen)
  10551. (while (org-up-heading-safe)
  10552. (when (looking-at org-complex-heading-regexp)
  10553. (push (org-trim
  10554. (replace-regexp-in-string
  10555. ;; Remove statistical/checkboxes cookies
  10556. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10557. (org-match-string-no-properties 4)))
  10558. rtn)))
  10559. rtn)))))
  10560. (defun org-format-outline-path (path &optional width prefix separator)
  10561. "Format the outline path PATH for display.
  10562. WIDTH is the maximum number of characters that is available.
  10563. PREFIX is a prefix to be included in the returned string,
  10564. such as the file name.
  10565. SEPARATOR is inserted between the different parts of the path,
  10566. the default is \"/\"."
  10567. (setq width (or width 79))
  10568. (setq path (delq nil path))
  10569. (unless (> width 0)
  10570. (user-error "Argument `width' must be positive"))
  10571. (setq separator (or separator "/"))
  10572. (let* ((org-odd-levels-only nil)
  10573. (fpath (concat
  10574. prefix (and prefix path separator)
  10575. (mapconcat
  10576. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10577. (loop for head in path
  10578. for n from 0
  10579. collect (org-add-props
  10580. head nil 'face
  10581. (nth (% n org-n-level-faces) org-level-faces)))
  10582. separator))))
  10583. (when (> (length fpath) width)
  10584. (if (< width 7)
  10585. ;; It's unlikely that `width' will be this small, but don't
  10586. ;; waste characters by adding ".." if it is.
  10587. (setq fpath (substring fpath 0 width))
  10588. (setf (substring fpath (- width 2)) "..")))
  10589. fpath))
  10590. (defun org-display-outline-path (&optional file current separator just-return-string)
  10591. "Display the current outline path in the echo area.
  10592. If FILE is non-nil, prepend the output with the file name.
  10593. If CURRENT is non-nil, append the current heading to the output.
  10594. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10595. the different parts of the path and defaults to \"/\".
  10596. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10597. (interactive "P")
  10598. (let* (case-fold-search
  10599. (bfn (buffer-file-name (buffer-base-buffer)))
  10600. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10601. res)
  10602. (when current (setq path (append path
  10603. (save-excursion
  10604. (org-back-to-heading t)
  10605. (when (looking-at org-complex-heading-regexp)
  10606. (list (match-string 4)))))))
  10607. (setq res
  10608. (org-format-outline-path
  10609. path
  10610. (1- (frame-width))
  10611. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10612. separator))
  10613. (if just-return-string
  10614. (org-no-properties res)
  10615. (org-unlogged-message "%s" res))))
  10616. (defvar org-refile-history nil
  10617. "History for refiling operations.")
  10618. (defvar org-after-refile-insert-hook nil
  10619. "Hook run after `org-refile' has inserted its stuff at the new location.
  10620. Note that this is still *before* the stuff will be removed from
  10621. the *old* location.")
  10622. (defvar org-capture-last-stored-marker)
  10623. (defvar org-refile-keep nil
  10624. "Non-nil means `org-refile' will copy instead of refile.")
  10625. (defun org-copy ()
  10626. "Like `org-refile', but copy."
  10627. (interactive)
  10628. (let ((org-refile-keep t))
  10629. (funcall 'org-refile nil nil nil "Copy")))
  10630. (defun org-refile (&optional arg default-buffer rfloc msg)
  10631. "Move the entry or entries at point to another heading.
  10632. The list of target headings is compiled using the information in
  10633. `org-refile-targets', which see.
  10634. At the target location, the entry is filed as a subitem of the
  10635. target heading. Depending on `org-reverse-note-order', the new
  10636. subitem will either be the first or the last subitem.
  10637. If there is an active region, all entries in that region will be
  10638. refiled. However, the region must fulfill the requirement that
  10639. the first heading sets the top-level of the moved text.
  10640. With prefix arg ARG, the command will only visit the target
  10641. location and not actually move anything.
  10642. With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
  10643. refiling operation has put the subtree.
  10644. With a numeric prefix argument of `2', refile to the running clock.
  10645. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10646. being set to t and copy to the target location, don't move it.
  10647. Beware that keeping refiled entries may result in duplicated ID
  10648. properties.
  10649. RFLOC can be a refile location obtained in a different way.
  10650. MSG is a string to replace \"Refile\" in the default prompt with
  10651. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10652. See also `org-refile-use-outline-path' and `org-completion-use-ido'.
  10653. If you are using target caching (see `org-refile-use-cache'), you
  10654. have to clear the target cache in order to find new targets.
  10655. This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
  10656. prefix argument (`C-u C-u C-u C-c C-w')."
  10657. (interactive "P")
  10658. (if (member arg '(0 (64)))
  10659. (org-refile-cache-clear)
  10660. (let* ((actionmsg (cond (msg msg)
  10661. ((equal arg 3) "Refile (and keep)")
  10662. (t "Refile")))
  10663. (cbuf (current-buffer))
  10664. (regionp (org-region-active-p))
  10665. (region-start (and regionp (region-beginning)))
  10666. (region-end (and regionp (region-end)))
  10667. (filename (buffer-file-name (buffer-base-buffer cbuf)))
  10668. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10669. pos it nbuf file re level reversed)
  10670. (setq last-command nil)
  10671. (when regionp
  10672. (goto-char region-start)
  10673. (or (bolp) (goto-char (point-at-bol)))
  10674. (setq region-start (point))
  10675. (unless (or (org-kill-is-subtree-p
  10676. (buffer-substring region-start region-end))
  10677. (prog1 org-refile-active-region-within-subtree
  10678. (let ((s (point-at-eol)))
  10679. (org-toggle-heading)
  10680. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10681. (user-error "The region is not a (sequence of) subtree(s)")))
  10682. (if (equal arg '(16))
  10683. (org-refile-goto-last-stored)
  10684. (when (or
  10685. (and (equal arg 2)
  10686. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10687. (prog1
  10688. (setq it (list (or org-clock-heading "running clock")
  10689. (buffer-file-name
  10690. (marker-buffer org-clock-hd-marker))
  10691. ""
  10692. (marker-position org-clock-hd-marker)))
  10693. (setq arg nil)))
  10694. (setq it (or rfloc
  10695. (let (heading-text)
  10696. (save-excursion
  10697. (unless (and arg (listp arg))
  10698. (org-back-to-heading t)
  10699. (setq heading-text
  10700. (replace-regexp-in-string
  10701. org-bracket-link-regexp
  10702. "\\3"
  10703. (nth 4 (org-heading-components)))))
  10704. (org-refile-get-location
  10705. (cond ((and arg (listp arg)) "Goto")
  10706. (regionp (concat actionmsg " region to"))
  10707. (t (concat actionmsg " subtree \""
  10708. heading-text "\" to")))
  10709. default-buffer
  10710. (and (not (equal '(4) arg))
  10711. org-refile-allow-creating-parent-nodes)
  10712. arg))))))
  10713. (setq file (nth 1 it)
  10714. re (nth 2 it)
  10715. pos (nth 3 it))
  10716. (when (and (not arg)
  10717. pos
  10718. (equal (buffer-file-name) file)
  10719. (if regionp
  10720. (and (>= pos region-start)
  10721. (<= pos region-end))
  10722. (and (>= pos (point))
  10723. (< pos (save-excursion
  10724. (org-end-of-subtree t t))))))
  10725. (error "Cannot refile to position inside the tree or region"))
  10726. (setq nbuf (or (find-buffer-visiting file)
  10727. (find-file-noselect file)))
  10728. (if (and arg (not (equal arg 3)))
  10729. (progn
  10730. (org-pop-to-buffer-same-window nbuf)
  10731. (goto-char pos)
  10732. (org-show-context 'org-goto))
  10733. (if regionp
  10734. (progn
  10735. (org-kill-new (buffer-substring region-start region-end))
  10736. (org-save-markers-in-region region-start region-end))
  10737. (org-copy-subtree 1 nil t))
  10738. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10739. (find-file-noselect file)))
  10740. (setq reversed (org-notes-order-reversed-p))
  10741. (save-excursion
  10742. (save-restriction
  10743. (widen)
  10744. (if pos
  10745. (progn
  10746. (goto-char pos)
  10747. (looking-at org-outline-regexp)
  10748. (setq level (org-get-valid-level (funcall outline-level) 1))
  10749. (goto-char
  10750. (if reversed
  10751. (or (outline-next-heading) (point-max))
  10752. (or (save-excursion (org-get-next-sibling))
  10753. (org-end-of-subtree t t)
  10754. (point-max)))))
  10755. (setq level 1)
  10756. (if (not reversed)
  10757. (goto-char (point-max))
  10758. (goto-char (point-min))
  10759. (or (outline-next-heading) (goto-char (point-max)))))
  10760. (unless (bolp) (newline))
  10761. (org-paste-subtree level nil nil t)
  10762. (when org-log-refile
  10763. (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
  10764. (unless (eq org-log-refile 'note)
  10765. (save-excursion (org-add-log-note))))
  10766. (and org-auto-align-tags
  10767. (let ((org-loop-over-headlines-in-active-region nil))
  10768. (org-set-tags nil t)))
  10769. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10770. :last-refile)))
  10771. (when bookmark-name
  10772. (with-demoted-errors
  10773. (bookmark-set bookmark-name))))
  10774. ;; If we are refiling for capture, make sure that the
  10775. ;; last-capture pointers point here
  10776. (when (org-bound-and-true-p org-refile-for-capture)
  10777. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10778. :last-capture-marker)))
  10779. (when bookmark-name
  10780. (with-demoted-errors
  10781. (bookmark-set bookmark-name))))
  10782. (move-marker org-capture-last-stored-marker (point)))
  10783. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10784. (run-hooks 'org-after-refile-insert-hook))))
  10785. (unless org-refile-keep
  10786. (if regionp
  10787. (delete-region (point) (+ (point) (- region-end region-start)))
  10788. (delete-region
  10789. (and (org-back-to-heading t) (point))
  10790. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10791. (when (featurep 'org-inlinetask)
  10792. (org-inlinetask-remove-END-maybe))
  10793. (setq org-markers-to-move nil)
  10794. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10795. (defun org-refile-goto-last-stored ()
  10796. "Go to the location where the last refile was stored."
  10797. (interactive)
  10798. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10799. (message "This is the location of the last refile"))
  10800. (defun org-refile--get-location (refloc tbl)
  10801. "When user refile to REFLOC, find the associated target in TBL.
  10802. Also check `org-refile-target-table'."
  10803. (car (delq
  10804. nil
  10805. (mapcar
  10806. (lambda (r) (or (assoc r tbl)
  10807. (assoc r org-refile-target-table)))
  10808. (list (replace-regexp-in-string "/$" "" refloc)
  10809. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10810. (defun org-refile-get-location (&optional prompt default-buffer new-nodes
  10811. no-exclude)
  10812. "Prompt the user for a refile location, using PROMPT.
  10813. PROMPT should not be suffixed with a colon and a space, because
  10814. this function appends the default value from
  10815. `org-refile-history' automatically, if that is not empty.
  10816. When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
  10817. this is used for the GOTO interface."
  10818. (let ((org-refile-targets org-refile-targets)
  10819. (org-refile-use-outline-path org-refile-use-outline-path)
  10820. excluded-entries)
  10821. (when (and (derived-mode-p 'org-mode)
  10822. (not org-refile-use-cache)
  10823. (not no-exclude))
  10824. (org-map-tree
  10825. (lambda()
  10826. (setq excluded-entries
  10827. (append excluded-entries (list (org-get-heading t t)))))))
  10828. (setq org-refile-target-table
  10829. (org-refile-get-targets default-buffer excluded-entries)))
  10830. (unless org-refile-target-table
  10831. (user-error "No refile targets"))
  10832. (let* ((cbuf (current-buffer))
  10833. (partial-completion-mode nil)
  10834. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10835. (cfunc (if (and org-refile-use-outline-path
  10836. org-outline-path-complete-in-steps)
  10837. 'org-olpath-completing-read
  10838. 'org-icompleting-read))
  10839. (extra (if org-refile-use-outline-path "/" ""))
  10840. (cbnex (concat (buffer-name) extra))
  10841. (filename (and cfn (expand-file-name cfn)))
  10842. (tbl (mapcar
  10843. (lambda (x)
  10844. (if (and (not (member org-refile-use-outline-path
  10845. '(file full-file-path)))
  10846. (not (equal filename (nth 1 x))))
  10847. (cons (concat (car x) extra " ("
  10848. (file-name-nondirectory (nth 1 x)) ")")
  10849. (cdr x))
  10850. (cons (concat (car x) extra) (cdr x))))
  10851. org-refile-target-table))
  10852. (completion-ignore-case t)
  10853. cdef
  10854. (prompt (concat prompt
  10855. (or (and (car org-refile-history)
  10856. (concat " (default " (car org-refile-history) ")"))
  10857. (and (assoc cbnex tbl) (setq cdef cbnex)
  10858. (concat " (default " cbnex ")"))) ": "))
  10859. pa answ parent-target child parent old-hist)
  10860. (setq old-hist org-refile-history)
  10861. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10862. nil 'org-refile-history (or cdef (car org-refile-history))))
  10863. (if (setq pa (org-refile--get-location answ tbl))
  10864. (progn
  10865. (org-refile-check-position pa)
  10866. (when (or (not org-refile-history)
  10867. (not (eq old-hist org-refile-history))
  10868. (not (equal (car pa) (car org-refile-history))))
  10869. (setq org-refile-history
  10870. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10871. org-refile-history
  10872. (cdr org-refile-history))))
  10873. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10874. (pop org-refile-history)))
  10875. pa)
  10876. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10877. (progn
  10878. (setq parent (match-string 1 answ)
  10879. child (match-string 2 answ))
  10880. (setq parent-target (org-refile--get-location parent tbl))
  10881. (when (and parent-target
  10882. (or (eq new-nodes t)
  10883. (and (eq new-nodes 'confirm)
  10884. (y-or-n-p (format "Create new node \"%s\"? "
  10885. child)))))
  10886. (org-refile-new-child parent-target child)))
  10887. (user-error "Invalid target location")))))
  10888. (declare-function org-string-nw-p "org-macs" (s))
  10889. (defun org-refile-check-position (refile-pointer)
  10890. "Check if the refile pointer matches the headline to which it points."
  10891. (let* ((file (nth 1 refile-pointer))
  10892. (re (nth 2 refile-pointer))
  10893. (pos (nth 3 refile-pointer))
  10894. buffer)
  10895. (if (and (not (markerp pos)) (not file))
  10896. (user-error "Please indicate a target file in the refile path")
  10897. (when (org-string-nw-p re)
  10898. (setq buffer (if (markerp pos)
  10899. (marker-buffer pos)
  10900. (or (find-buffer-visiting file)
  10901. (find-file-noselect file))))
  10902. (with-current-buffer buffer
  10903. (save-excursion
  10904. (save-restriction
  10905. (widen)
  10906. (goto-char pos)
  10907. (beginning-of-line 1)
  10908. (unless (org-looking-at-p re)
  10909. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
  10910. (defun org-refile-new-child (parent-target child)
  10911. "Use refile target PARENT-TARGET to add new CHILD below it."
  10912. (unless parent-target
  10913. (error "Cannot find parent for new node"))
  10914. (let ((file (nth 1 parent-target))
  10915. (pos (nth 3 parent-target))
  10916. level)
  10917. (with-current-buffer (or (find-buffer-visiting file)
  10918. (find-file-noselect file))
  10919. (save-excursion
  10920. (save-restriction
  10921. (widen)
  10922. (if pos
  10923. (goto-char pos)
  10924. (goto-char (point-max))
  10925. (unless (bolp) (newline)))
  10926. (when (looking-at org-outline-regexp)
  10927. (setq level (funcall outline-level))
  10928. (org-end-of-subtree t t))
  10929. (org-back-over-empty-lines)
  10930. (insert "\n" (make-string
  10931. (if pos (org-get-valid-level level 1) 1) ?*)
  10932. " " child "\n")
  10933. (beginning-of-line 0)
  10934. (list (concat (car parent-target) "/" child) file "" (point)))))))
  10935. (defun org-olpath-completing-read (prompt collection &rest args)
  10936. "Read an outline path like a file name."
  10937. (let ((thetable collection)
  10938. (org-completion-use-ido nil) ; does not work with ido.
  10939. (org-completion-use-iswitchb nil)) ; or iswitchb
  10940. (apply #'org-icompleting-read
  10941. prompt
  10942. (lambda (string predicate &optional flag)
  10943. (cond
  10944. ((eq flag nil) (try-completion string thetable))
  10945. ((eq flag t)
  10946. (let ((l (length string)))
  10947. (mapcar (lambda (x)
  10948. (let ((r (substring x l))
  10949. (f (if (string-match " ([^)]*)$" x)
  10950. (match-string 0 x)
  10951. "")))
  10952. (if (string-match "/" r)
  10953. (concat string (substring r 0 (match-end 0)) f)
  10954. x)))
  10955. (all-completions string thetable predicate))))
  10956. ;; Exact match?
  10957. ((eq flag 'lambda) (assoc string thetable))))
  10958. args)))
  10959. ;;;; Dynamic blocks
  10960. (defun org-find-dblock (name)
  10961. "Find the first dynamic block with name NAME in the buffer.
  10962. If not found, stay at current position and return nil."
  10963. (let ((case-fold-search t) pos)
  10964. (save-excursion
  10965. (goto-char (point-min))
  10966. (setq pos (and (re-search-forward
  10967. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10968. (match-beginning 0))))
  10969. (when pos (goto-char pos))
  10970. pos))
  10971. (defun org-create-dblock (plist)
  10972. "Create a dynamic block section, with parameters taken from PLIST.
  10973. PLIST must contain a :name entry which is used as the name of the block."
  10974. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10975. (end-of-line 1)
  10976. (newline))
  10977. (let ((col (current-column))
  10978. (name (plist-get plist :name)))
  10979. (insert "#+BEGIN: " name)
  10980. (while plist
  10981. (if (eq (car plist) :name)
  10982. (setq plist (cddr plist))
  10983. (insert " " (prin1-to-string (pop plist)))))
  10984. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10985. (beginning-of-line -2)))
  10986. (defun org-prepare-dblock ()
  10987. "Prepare dynamic block for refresh.
  10988. This empties the block, puts the cursor at the insert position and returns
  10989. the property list including an extra property :name with the block name."
  10990. (unless (looking-at org-dblock-start-re)
  10991. (user-error "Not at a dynamic block"))
  10992. (let* ((begdel (1+ (match-end 0)))
  10993. (name (org-no-properties (match-string 1)))
  10994. (params (append (list :name name)
  10995. (read (concat "(" (match-string 3) ")")))))
  10996. (save-excursion
  10997. (beginning-of-line 1)
  10998. (skip-chars-forward " \t")
  10999. (setq params (plist-put params :indentation-column (current-column))))
  11000. (unless (re-search-forward org-dblock-end-re nil t)
  11001. (error "Dynamic block not terminated"))
  11002. (setq params
  11003. (append params
  11004. (list :content (buffer-substring
  11005. begdel (match-beginning 0)))))
  11006. (delete-region begdel (match-beginning 0))
  11007. (goto-char begdel)
  11008. (open-line 1)
  11009. params))
  11010. (defun org-map-dblocks (&optional command)
  11011. "Apply COMMAND to all dynamic blocks in the current buffer.
  11012. If COMMAND is not given, use `org-update-dblock'."
  11013. (let ((cmd (or command 'org-update-dblock)))
  11014. (save-excursion
  11015. (goto-char (point-min))
  11016. (while (re-search-forward org-dblock-start-re nil t)
  11017. (goto-char (match-beginning 0))
  11018. (save-excursion
  11019. (condition-case nil
  11020. (funcall cmd)
  11021. (error (message "Error during update of dynamic block"))))
  11022. (unless (re-search-forward org-dblock-end-re nil t)
  11023. (error "Dynamic block not terminated"))))))
  11024. (defun org-dblock-update (&optional arg)
  11025. "User command for updating dynamic blocks.
  11026. Update the dynamic block at point. With prefix ARG, update all dynamic
  11027. blocks in the buffer."
  11028. (interactive "P")
  11029. (if arg
  11030. (org-update-all-dblocks)
  11031. (or (looking-at org-dblock-start-re)
  11032. (org-beginning-of-dblock))
  11033. (org-update-dblock)))
  11034. (defun org-update-dblock ()
  11035. "Update the dynamic block at point.
  11036. This means to empty the block, parse for parameters and then call
  11037. the correct writing function."
  11038. (interactive)
  11039. (save-excursion
  11040. (let* ((win (selected-window))
  11041. (pos (point))
  11042. (line (org-current-line))
  11043. (params (org-prepare-dblock))
  11044. (name (plist-get params :name))
  11045. (indent (plist-get params :indentation-column))
  11046. (cmd (intern (concat "org-dblock-write:" name))))
  11047. (message "Updating dynamic block `%s' at line %d..." name line)
  11048. (funcall cmd params)
  11049. (message "Updating dynamic block `%s' at line %d...done" name line)
  11050. (goto-char pos)
  11051. (when (and indent (> indent 0))
  11052. (setq indent (make-string indent ?\ ))
  11053. (save-excursion
  11054. (select-window win)
  11055. (org-beginning-of-dblock)
  11056. (forward-line 1)
  11057. (while (not (looking-at org-dblock-end-re))
  11058. (insert indent)
  11059. (beginning-of-line 2))
  11060. (when (looking-at org-dblock-end-re)
  11061. (and (looking-at "[ \t]+")
  11062. (replace-match ""))
  11063. (insert indent)))))))
  11064. (defun org-beginning-of-dblock ()
  11065. "Find the beginning of the dynamic block at point.
  11066. Error if there is no such block at point."
  11067. (let ((pos (point))
  11068. beg)
  11069. (end-of-line 1)
  11070. (if (and (re-search-backward org-dblock-start-re nil t)
  11071. (setq beg (match-beginning 0))
  11072. (re-search-forward org-dblock-end-re nil t)
  11073. (> (match-end 0) pos))
  11074. (goto-char beg)
  11075. (goto-char pos)
  11076. (error "Not in a dynamic block"))))
  11077. (defun org-update-all-dblocks ()
  11078. "Update all dynamic blocks in the buffer.
  11079. This function can be used in a hook."
  11080. (interactive)
  11081. (when (derived-mode-p 'org-mode)
  11082. (org-map-dblocks 'org-update-dblock)))
  11083. ;;;; Completion
  11084. (declare-function org-export-backend-name "org-export" (cl-x))
  11085. (declare-function org-export-backend-options "org-export" (cl-x))
  11086. (defun org-get-export-keywords ()
  11087. "Return a list of all currently understood export keywords.
  11088. Export keywords include options, block names, attributes and
  11089. keywords relative to each registered export back-end."
  11090. (let (keywords)
  11091. (dolist (backend
  11092. (org-bound-and-true-p org-export-registered-backends)
  11093. (delq nil keywords))
  11094. ;; Back-end name (for keywords, like #+LATEX:)
  11095. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11096. (dolist (option-entry (org-export-backend-options backend))
  11097. ;; Back-end options.
  11098. (push (nth 1 option-entry) keywords)))))
  11099. (defconst org-options-keywords
  11100. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11101. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11102. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11103. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11104. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11105. (defcustom org-structure-template-alist
  11106. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11107. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11108. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11109. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11110. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11111. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11112. ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
  11113. ("L" "#+LaTeX: ")
  11114. ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
  11115. ("H" "#+HTML: ")
  11116. ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
  11117. ("A" "#+ASCII: ")
  11118. ("i" "#+INDEX: ?")
  11119. ("I" "#+INCLUDE: %file ?"))
  11120. "Structure completion elements.
  11121. This is a list of abbreviation keys and values. The value gets inserted
  11122. if you type `<' followed by the key and then press the completion key,
  11123. usually `TAB'. %file will be replaced by a file name after prompting
  11124. for the file using completion. The cursor will be placed at the position
  11125. of the `?' in the template.
  11126. There are two templates for each key, the first uses the original Org syntax,
  11127. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11128. the default when the /org-mtags.el/ module has been loaded. See also the
  11129. variable `org-mtags-prefer-muse-templates'."
  11130. :group 'org-completion
  11131. :type '(repeat
  11132. (list
  11133. (string :tag "Key")
  11134. (string :tag "Template")))
  11135. :version "25.1"
  11136. :package-version '(Org . "8.3"))
  11137. (defun org-try-structure-completion ()
  11138. "Try to complete a structure template before point.
  11139. This looks for strings like \"<e\" on an otherwise empty line and
  11140. expands them."
  11141. (let ((l (buffer-substring (point-at-bol) (point)))
  11142. a)
  11143. (when (and (looking-at "[ \t]*$")
  11144. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11145. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11146. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11147. (match-beginning 1)) a)
  11148. t)))
  11149. (defun org-complete-expand-structure-template (start cell)
  11150. "Expand a structure template."
  11151. (let ((rpl (nth 1 cell))
  11152. (ind ""))
  11153. (delete-region start (point))
  11154. (when (string-match "\\`[ \t]*#\\+" rpl)
  11155. (cond
  11156. ((bolp))
  11157. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11158. (setq ind (buffer-substring (point-at-bol) (point))))
  11159. (t (newline))))
  11160. (setq start (point))
  11161. (when (string-match "%file" rpl)
  11162. (setq rpl (replace-match
  11163. (concat
  11164. "\""
  11165. (save-match-data
  11166. (abbreviate-file-name (read-file-name "Include file: ")))
  11167. "\"")
  11168. t t rpl)))
  11169. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11170. (concat "\n" ind)))
  11171. (insert rpl)
  11172. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11173. ;;;; TODO, DEADLINE, Comments
  11174. (defun org-toggle-comment ()
  11175. "Change the COMMENT state of an entry."
  11176. (interactive)
  11177. (save-excursion
  11178. (org-back-to-heading)
  11179. (looking-at org-complex-heading-regexp)
  11180. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11181. (skip-chars-forward " \t")
  11182. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11183. (if (org-in-commented-heading-p t)
  11184. (delete-region (point)
  11185. (progn (search-forward " " (line-end-position) 'move)
  11186. (skip-chars-forward " \t")
  11187. (point)))
  11188. (insert org-comment-string)
  11189. (unless (eolp) (insert " ")))))
  11190. (defvar org-last-todo-state-is-todo nil
  11191. "This is non-nil when the last TODO state change led to a TODO state.
  11192. If the last change removed the TODO tag or switched to DONE, then
  11193. this is nil.")
  11194. (defvar org-setting-tags nil) ; dynamically skipped
  11195. (defvar org-todo-setup-filter-hook nil
  11196. "Hook for functions that pre-filter todo specs.
  11197. Each function takes a todo spec and returns either nil or the spec
  11198. transformed into canonical form." )
  11199. (defvar org-todo-get-default-hook nil
  11200. "Hook for functions that get a default item for todo.
  11201. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11202. nil or a string to be used for the todo mark." )
  11203. (defvar org-agenda-headline-snapshot-before-repeat)
  11204. (defun org-current-effective-time ()
  11205. "Return current time adjusted for `org-extend-today-until' variable."
  11206. (let* ((ct (org-current-time))
  11207. (dct (decode-time ct))
  11208. (ct1
  11209. (cond
  11210. (org-use-last-clock-out-time-as-effective-time
  11211. (or (org-clock-get-last-clock-out-time) ct))
  11212. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11213. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11214. (t ct))))
  11215. ct1))
  11216. (defun org-todo-yesterday (&optional arg)
  11217. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11218. (interactive "P")
  11219. (if (eq major-mode 'org-agenda-mode)
  11220. (apply 'org-agenda-todo-yesterday arg)
  11221. (let* ((org-use-effective-time t)
  11222. (hour (third (decode-time
  11223. (org-current-time))))
  11224. (org-extend-today-until (1+ hour)))
  11225. (org-todo arg))))
  11226. (defvar org-block-entry-blocking ""
  11227. "First entry preventing the TODO state change.")
  11228. (defun org-cancel-repeater ()
  11229. "Cancel a repeater by setting its numeric value to zero."
  11230. (interactive)
  11231. (save-excursion
  11232. (org-back-to-heading t)
  11233. (let ((bound1 (point))
  11234. (bound0 (save-excursion (outline-next-heading) (point))))
  11235. (when (and (re-search-forward
  11236. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11237. org-deadline-time-regexp "\\)\\|\\("
  11238. org-ts-regexp "\\)")
  11239. bound0 t)
  11240. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11241. bound1 t))
  11242. (replace-match "0" t nil nil 1)))))
  11243. (defun org-todo (&optional arg)
  11244. "Change the TODO state of an item.
  11245. The state of an item is given by a keyword at the start of the heading,
  11246. like
  11247. *** TODO Write paper
  11248. *** DONE Call mom
  11249. The different keywords are specified in the variable `org-todo-keywords'.
  11250. By default the available states are \"TODO\" and \"DONE\".
  11251. So for this example: when the item starts with TODO, it is changed to DONE.
  11252. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11253. DONE are present, add TODO at the beginning of the heading.
  11254. With \\[universal-argument] prefix arg, use completion to determine the new \
  11255. state.
  11256. With numeric prefix arg, switch to that state.
  11257. With a double \\[universal-argument] prefix, switch to the next set of TODO \
  11258. keywords (nextset).
  11259. With a triple \\[universal-argument] prefix, circumvent any state blocking.
  11260. With a numeric prefix arg of 0, inhibit note taking for the change.
  11261. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11262. When called through ELisp, arg is also interpreted in the following way:
  11263. `none' -> empty state
  11264. \"\"(empty string) -> switch to empty state
  11265. `done' -> switch to DONE
  11266. `nextset' -> switch to the next set of keywords
  11267. `previousset' -> switch to the previous set of keywords
  11268. \"WAITING\" -> switch to the specified keyword, but only if it
  11269. really is a member of `org-todo-keywords'."
  11270. (interactive "P")
  11271. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11272. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11273. 'region-start-level 'region))
  11274. org-loop-over-headlines-in-active-region)
  11275. (org-map-entries
  11276. `(org-todo ,arg)
  11277. org-loop-over-headlines-in-active-region
  11278. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11279. (when (equal arg '(16)) (setq arg 'nextset))
  11280. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11281. (let ((org-blocker-hook org-blocker-hook)
  11282. commentp
  11283. case-fold-search)
  11284. (when (equal arg '(64))
  11285. (setq arg nil org-blocker-hook nil))
  11286. (when (and org-blocker-hook
  11287. (or org-inhibit-blocking
  11288. (org-entry-get nil "NOBLOCKING")))
  11289. (setq org-blocker-hook nil))
  11290. (save-excursion
  11291. (catch 'exit
  11292. (org-back-to-heading t)
  11293. (when (org-in-commented-heading-p t)
  11294. (org-toggle-comment)
  11295. (setq commentp t))
  11296. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11297. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11298. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11299. (let* ((match-data (match-data))
  11300. (startpos (point-at-bol))
  11301. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11302. (org-log-done org-log-done)
  11303. (org-log-repeat org-log-repeat)
  11304. (org-todo-log-states org-todo-log-states)
  11305. (org-inhibit-logging
  11306. (if (equal arg 0)
  11307. (progn (setq arg nil) 'note) org-inhibit-logging))
  11308. (this (match-string 1))
  11309. (hl-pos (match-beginning 0))
  11310. (head (org-get-todo-sequence-head this))
  11311. (ass (assoc head org-todo-kwd-alist))
  11312. (interpret (nth 1 ass))
  11313. (done-word (nth 3 ass))
  11314. (final-done-word (nth 4 ass))
  11315. (org-last-state (or this ""))
  11316. (completion-ignore-case t)
  11317. (member (member this org-todo-keywords-1))
  11318. (tail (cdr member))
  11319. (org-state (cond
  11320. ((and org-todo-key-trigger
  11321. (or (and (equal arg '(4))
  11322. (eq org-use-fast-todo-selection 'prefix))
  11323. (and (not arg) org-use-fast-todo-selection
  11324. (not (eq org-use-fast-todo-selection
  11325. 'prefix)))))
  11326. ;; Use fast selection
  11327. (org-fast-todo-selection))
  11328. ((and (equal arg '(4))
  11329. (or (not org-use-fast-todo-selection)
  11330. (not org-todo-key-trigger)))
  11331. ;; Read a state with completion
  11332. (org-icompleting-read
  11333. "State: " (mapcar 'list org-todo-keywords-1)
  11334. nil t))
  11335. ((eq arg 'right)
  11336. (if this
  11337. (if tail (car tail) nil)
  11338. (car org-todo-keywords-1)))
  11339. ((eq arg 'left)
  11340. (unless (equal member org-todo-keywords-1)
  11341. (if this
  11342. (nth (- (length org-todo-keywords-1)
  11343. (length tail) 2)
  11344. org-todo-keywords-1)
  11345. (org-last org-todo-keywords-1))))
  11346. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11347. (setq arg nil))) ; hack to fall back to cycling
  11348. (arg
  11349. ;; user or caller requests a specific state
  11350. (cond
  11351. ((equal arg "") nil)
  11352. ((eq arg 'none) nil)
  11353. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11354. ((eq arg 'nextset)
  11355. (or (car (cdr (member head org-todo-heads)))
  11356. (car org-todo-heads)))
  11357. ((eq arg 'previousset)
  11358. (let ((org-todo-heads (reverse org-todo-heads)))
  11359. (or (car (cdr (member head org-todo-heads)))
  11360. (car org-todo-heads))))
  11361. ((car (member arg org-todo-keywords-1)))
  11362. ((stringp arg)
  11363. (user-error "State `%s' not valid in this file" arg))
  11364. ((nth (1- (prefix-numeric-value arg))
  11365. org-todo-keywords-1))))
  11366. ((null member) (or head (car org-todo-keywords-1)))
  11367. ((equal this final-done-word) nil) ;; -> make empty
  11368. ((null tail) nil) ;; -> first entry
  11369. ((memq interpret '(type priority))
  11370. (if (eq this-command last-command)
  11371. (car tail)
  11372. (if (> (length tail) 0)
  11373. (or done-word (car org-done-keywords))
  11374. nil)))
  11375. (t
  11376. (car tail))))
  11377. (org-state (or
  11378. (run-hook-with-args-until-success
  11379. 'org-todo-get-default-hook org-state org-last-state)
  11380. org-state))
  11381. (next (if org-state (concat " " org-state " ") " "))
  11382. (change-plist (list :type 'todo-state-change :from this :to org-state
  11383. :position startpos))
  11384. dolog now-done-p)
  11385. (when org-blocker-hook
  11386. (setq org-last-todo-state-is-todo
  11387. (not (member this org-done-keywords)))
  11388. (unless (save-excursion
  11389. (save-match-data
  11390. (org-with-wide-buffer
  11391. (run-hook-with-args-until-failure
  11392. 'org-blocker-hook change-plist))))
  11393. (if (org-called-interactively-p 'interactive)
  11394. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11395. this org-state org-block-entry-blocking)
  11396. ;; fail silently
  11397. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11398. this org-state org-block-entry-blocking)
  11399. (throw 'exit nil))))
  11400. (store-match-data match-data)
  11401. (replace-match next t t)
  11402. (cond ((equal this org-state)
  11403. (message "TODO state was already %s" (org-trim next)))
  11404. ((pos-visible-in-window-p hl-pos)
  11405. (message "TODO state changed to %s" (org-trim next))))
  11406. (unless head
  11407. (setq head (org-get-todo-sequence-head org-state)
  11408. ass (assoc head org-todo-kwd-alist)
  11409. interpret (nth 1 ass)
  11410. done-word (nth 3 ass)
  11411. final-done-word (nth 4 ass)))
  11412. (when (memq arg '(nextset previousset))
  11413. (message "Keyword-Set %d/%d: %s"
  11414. (- (length org-todo-sets) -1
  11415. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11416. (length org-todo-sets)
  11417. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11418. (setq org-last-todo-state-is-todo
  11419. (not (member org-state org-done-keywords)))
  11420. (setq now-done-p (and (member org-state org-done-keywords)
  11421. (not (member this org-done-keywords))))
  11422. (and logging (org-local-logging logging))
  11423. (when (and (or org-todo-log-states org-log-done)
  11424. (not (eq org-inhibit-logging t))
  11425. (not (memq arg '(nextset previousset))))
  11426. ;; we need to look at recording a time and note
  11427. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11428. (nth 2 (assoc this org-todo-log-states))))
  11429. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11430. (setq dolog 'time))
  11431. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11432. (and org-state
  11433. (member org-state org-not-done-keywords)
  11434. (not (member this org-not-done-keywords))))
  11435. ;; This is now a todo state and was not one before
  11436. ;; If there was a CLOSED time stamp, get rid of it.
  11437. (org-add-planning-info nil nil 'closed))
  11438. (when (and now-done-p org-log-done)
  11439. ;; It is now done, and it was not done before
  11440. (org-add-planning-info 'closed (org-current-effective-time))
  11441. (when (and (not dolog) (eq 'note org-log-done))
  11442. (org-add-log-setup 'done org-state this 'findpos 'note)))
  11443. (when (and org-state dolog)
  11444. ;; This is a non-nil state, and we need to log it
  11445. (org-add-log-setup 'state org-state this 'findpos dolog)))
  11446. ;; Fixup tag positioning
  11447. (org-todo-trigger-tag-changes org-state)
  11448. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11449. (when org-provide-todo-statistics
  11450. (org-update-parent-todo-statistics))
  11451. (run-hooks 'org-after-todo-state-change-hook)
  11452. (when (and arg (not (member org-state org-done-keywords)))
  11453. (setq head (org-get-todo-sequence-head org-state)))
  11454. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11455. ;; Do we need to trigger a repeat?
  11456. (when now-done-p
  11457. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11458. ;; This is for the agenda, take a snapshot of the headline.
  11459. (save-match-data
  11460. (setq org-agenda-headline-snapshot-before-repeat
  11461. (org-get-heading))))
  11462. (org-auto-repeat-maybe org-state))
  11463. ;; Fixup cursor location if close to the keyword
  11464. (when (and (outline-on-heading-p)
  11465. (not (bolp))
  11466. (save-excursion (beginning-of-line 1)
  11467. (looking-at org-todo-line-regexp))
  11468. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11469. (goto-char (or (match-end 2) (match-end 1)))
  11470. (and (looking-at " ") (just-one-space)))
  11471. (when org-trigger-hook
  11472. (save-excursion
  11473. (run-hook-with-args 'org-trigger-hook change-plist)))
  11474. (when commentp (org-toggle-comment))))))))
  11475. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11476. "Block turning an entry into a TODO, using the hierarchy.
  11477. This checks whether the current task should be blocked from state
  11478. changes. Such blocking occurs when:
  11479. 1. The task has children which are not all in a completed state.
  11480. 2. A task has a parent with the property :ORDERED:, and there
  11481. are siblings prior to the current task with incomplete
  11482. status.
  11483. 3. The parent of the task is blocked because it has siblings that should
  11484. be done first, or is child of a block grandparent TODO entry."
  11485. (if (not org-enforce-todo-dependencies)
  11486. t ; if locally turned off don't block
  11487. (catch 'dont-block
  11488. ;; If this is not a todo state change, or if this entry is already DONE,
  11489. ;; do not block
  11490. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11491. (member (plist-get change-plist :from)
  11492. (cons 'done org-done-keywords))
  11493. (member (plist-get change-plist :to)
  11494. (cons 'todo org-not-done-keywords))
  11495. (not (plist-get change-plist :to)))
  11496. (throw 'dont-block t))
  11497. ;; If this task has children, and any are undone, it's blocked
  11498. (save-excursion
  11499. (org-back-to-heading t)
  11500. (let ((this-level (funcall outline-level)))
  11501. (outline-next-heading)
  11502. (let ((child-level (funcall outline-level)))
  11503. (while (and (not (eobp))
  11504. (> child-level this-level))
  11505. ;; this todo has children, check whether they are all
  11506. ;; completed
  11507. (when (and (not (org-entry-is-done-p))
  11508. (org-entry-is-todo-p))
  11509. (setq org-block-entry-blocking (org-get-heading))
  11510. (throw 'dont-block nil))
  11511. (outline-next-heading)
  11512. (setq child-level (funcall outline-level))))))
  11513. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11514. ;; any previous siblings are undone, it's blocked
  11515. (save-excursion
  11516. (org-back-to-heading t)
  11517. (let* ((pos (point))
  11518. (parent-pos (and (org-up-heading-safe) (point))))
  11519. (unless parent-pos (throw 'dont-block t)) ; no parent
  11520. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11521. (forward-line 1)
  11522. (re-search-forward org-not-done-heading-regexp pos t))
  11523. (setq org-block-entry-blocking (match-string 0))
  11524. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11525. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11526. (while t
  11527. (goto-char parent-pos)
  11528. (unless (looking-at org-not-done-heading-regexp)
  11529. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11530. (setq pos (point))
  11531. (setq parent-pos (and (org-up-heading-safe) (point)))
  11532. (unless parent-pos (throw 'dont-block t)) ; no parent
  11533. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11534. (forward-line 1)
  11535. (re-search-forward org-not-done-heading-regexp pos t)
  11536. (setq org-block-entry-blocking (org-get-heading)))
  11537. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11538. (defcustom org-track-ordered-property-with-tag nil
  11539. "Should the ORDERED property also be shown as a tag?
  11540. The ORDERED property decides if an entry should require subtasks to be
  11541. completed in sequence. Since a property is not very visible, setting
  11542. this option means that toggling the ORDERED property with the command
  11543. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11544. not relevant for the behavior, but it makes things more visible.
  11545. Note that toggling the tag with tags commands will not change the property
  11546. and therefore not influence behavior!
  11547. This can be t, meaning the tag ORDERED should be used, It can also be a
  11548. string to select a different tag for this task."
  11549. :group 'org-todo
  11550. :type '(choice
  11551. (const :tag "No tracking" nil)
  11552. (const :tag "Track with ORDERED tag" t)
  11553. (string :tag "Use other tag")))
  11554. (defun org-toggle-ordered-property ()
  11555. "Toggle the ORDERED property of the current entry.
  11556. For better visibility, you can track the value of this property with a tag.
  11557. See variable `org-track-ordered-property-with-tag'."
  11558. (interactive)
  11559. (let* ((t1 org-track-ordered-property-with-tag)
  11560. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11561. (save-excursion
  11562. (org-back-to-heading)
  11563. (if (org-entry-get nil "ORDERED")
  11564. (progn
  11565. (org-delete-property "ORDERED")
  11566. (and tag (org-toggle-tag tag 'off))
  11567. (message "Subtasks can be completed in arbitrary order"))
  11568. (org-entry-put nil "ORDERED" "t")
  11569. (and tag (org-toggle-tag tag 'on))
  11570. (message "Subtasks must be completed in sequence")))))
  11571. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11572. (defun org-block-todo-from-checkboxes (change-plist)
  11573. "Block turning an entry into a TODO, using checkboxes.
  11574. This checks whether the current task should be blocked from state
  11575. changes because there are unchecked boxes in this entry."
  11576. (if (not org-enforce-todo-checkbox-dependencies)
  11577. t ; if locally turned off don't block
  11578. (catch 'dont-block
  11579. ;; If this is not a todo state change, or if this entry is already DONE,
  11580. ;; do not block
  11581. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11582. (member (plist-get change-plist :from)
  11583. (cons 'done org-done-keywords))
  11584. (member (plist-get change-plist :to)
  11585. (cons 'todo org-not-done-keywords))
  11586. (not (plist-get change-plist :to)))
  11587. (throw 'dont-block t))
  11588. ;; If this task has checkboxes that are not checked, it's blocked
  11589. (save-excursion
  11590. (org-back-to-heading t)
  11591. (let ((beg (point)) end)
  11592. (outline-next-heading)
  11593. (setq end (point))
  11594. (goto-char beg)
  11595. (when (org-list-search-forward
  11596. (concat (org-item-beginning-re)
  11597. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11598. "\\[[- ]\\]")
  11599. end t)
  11600. (when (boundp 'org-blocked-by-checkboxes)
  11601. (setq org-blocked-by-checkboxes t))
  11602. (throw 'dont-block nil))))
  11603. t))) ; do not block
  11604. (defun org-entry-blocked-p ()
  11605. "Non-nil if entry at point is blocked."
  11606. (and (not (org-entry-get nil "NOBLOCKING"))
  11607. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11608. (not (run-hook-with-args-until-failure
  11609. 'org-blocker-hook
  11610. (list :type 'todo-state-change
  11611. :position (point)
  11612. :from 'todo
  11613. :to 'done)))))
  11614. (defun org-update-statistics-cookies (all)
  11615. "Update the statistics cookie, either from TODO or from checkboxes.
  11616. This should be called with the cursor in a line with a statistics cookie."
  11617. (interactive "P")
  11618. (if all
  11619. (progn
  11620. (org-update-checkbox-count 'all)
  11621. (org-map-entries 'org-update-parent-todo-statistics))
  11622. (if (not (org-at-heading-p))
  11623. (org-update-checkbox-count)
  11624. (let ((pos (point-marker))
  11625. end l1 l2)
  11626. (ignore-errors (org-back-to-heading t))
  11627. (if (not (org-at-heading-p))
  11628. (org-update-checkbox-count)
  11629. (setq l1 (org-outline-level))
  11630. (setq end (save-excursion
  11631. (outline-next-heading)
  11632. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11633. (point)))
  11634. (if (and (save-excursion
  11635. (re-search-forward
  11636. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11637. (not (save-excursion (re-search-forward
  11638. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11639. (org-update-checkbox-count)
  11640. (if (and l2 (> l2 l1))
  11641. (progn
  11642. (goto-char end)
  11643. (org-update-parent-todo-statistics))
  11644. (goto-char pos)
  11645. (beginning-of-line 1)
  11646. (while (re-search-forward
  11647. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11648. (point-at-eol) t)
  11649. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11650. (goto-char pos)
  11651. (move-marker pos nil)))))
  11652. (defvar org-entry-property-inherited-from) ;; defined below
  11653. (defun org-update-parent-todo-statistics ()
  11654. "Update any statistics cookie in the parent of the current headline.
  11655. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11656. the entire subtree and this will travel up the hierarchy and update
  11657. statistics everywhere."
  11658. (let* ((prop (save-excursion (org-up-heading-safe)
  11659. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11660. (recursive (or (not org-hierarchical-todo-statistics)
  11661. (and prop (string-match "\\<recursive\\>" prop))))
  11662. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11663. 0))
  11664. (first t)
  11665. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11666. level ltoggle l1 new ndel
  11667. (cnt-all 0) (cnt-done 0) is-percent kwd
  11668. checkbox-beg ov ovs ove cookie-present)
  11669. (catch 'exit
  11670. (save-excursion
  11671. (beginning-of-line 1)
  11672. (setq ltoggle (funcall outline-level))
  11673. ;; Three situations are to consider:
  11674. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11675. ;; to the top-level ancestor on the headline;
  11676. ;; 2. If parent has "recursive" property, repeat up to the
  11677. ;; headline setting that property, taking inheritance into
  11678. ;; account;
  11679. ;; 3. Else, move up to direct parent and proceed only once.
  11680. (while (and (setq level (org-up-heading-safe))
  11681. (or recursive first)
  11682. (>= (point) lim))
  11683. (setq first nil cookie-present nil)
  11684. (unless (and level
  11685. (not (string-match
  11686. "\\<checkbox\\>"
  11687. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11688. "")))))
  11689. (throw 'exit nil))
  11690. (while (re-search-forward box-re (point-at-eol) t)
  11691. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11692. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11693. (save-match-data
  11694. (unless (outline-next-heading) (throw 'exit nil))
  11695. (while (and (looking-at org-complex-heading-regexp)
  11696. (> (setq l1 (length (match-string 1))) level))
  11697. (setq kwd (and (or recursive (= l1 ltoggle))
  11698. (match-string 2)))
  11699. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11700. (and (eq org-provide-todo-statistics t)
  11701. (or (member kwd org-done-keywords)))
  11702. (and (listp org-provide-todo-statistics)
  11703. (stringp (car org-provide-todo-statistics))
  11704. (or (member kwd org-provide-todo-statistics)
  11705. (member kwd org-done-keywords)))
  11706. (and (listp org-provide-todo-statistics)
  11707. (listp (car org-provide-todo-statistics))
  11708. (or (member kwd (car org-provide-todo-statistics))
  11709. (and (member kwd org-done-keywords)
  11710. (member kwd (cadr org-provide-todo-statistics))))))
  11711. (setq cnt-all (1+ cnt-all))
  11712. (and (eq org-provide-todo-statistics t)
  11713. kwd
  11714. (setq cnt-all (1+ cnt-all))))
  11715. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11716. (member kwd org-done-keywords))
  11717. (and (listp org-provide-todo-statistics)
  11718. (listp (car org-provide-todo-statistics))
  11719. (member kwd org-done-keywords)
  11720. (member kwd (cadr org-provide-todo-statistics)))
  11721. (and (listp org-provide-todo-statistics)
  11722. (stringp (car org-provide-todo-statistics))
  11723. (member kwd org-done-keywords)))
  11724. (setq cnt-done (1+ cnt-done)))
  11725. (outline-next-heading)))
  11726. (setq new
  11727. (if is-percent
  11728. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11729. (max 1 cnt-all)))
  11730. (format "[%d/%d]" cnt-done cnt-all))
  11731. ndel (- (match-end 0) checkbox-beg))
  11732. ;; handle overlays when updating cookie from column view
  11733. (when (setq ov (car (overlays-at checkbox-beg)))
  11734. (setq ovs (overlay-start ov) ove (overlay-end ov))
  11735. (delete-overlay ov))
  11736. (goto-char checkbox-beg)
  11737. (insert new)
  11738. (delete-region (point) (+ (point) ndel))
  11739. (when org-auto-align-tags (org-fix-tags-on-the-fly))
  11740. (when ov (move-overlay ov ovs ove)))
  11741. (when cookie-present
  11742. (run-hook-with-args 'org-after-todo-statistics-hook
  11743. cnt-done (- cnt-all cnt-done))))))
  11744. (run-hooks 'org-todo-statistics-hook)))
  11745. (defvar org-after-todo-statistics-hook nil
  11746. "Hook that is called after a TODO statistics cookie has been updated.
  11747. Each function is called with two arguments: the number of not-done entries
  11748. and the number of done entries.
  11749. For example, the following function, when added to this hook, will switch
  11750. an entry to DONE when all children are done, and back to TODO when new
  11751. entries are set to a TODO status. Note that this hook is only called
  11752. when there is a statistics cookie in the headline!
  11753. (defun org-summary-todo (n-done n-not-done)
  11754. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11755. (let (org-log-done org-log-states) ; turn off logging
  11756. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11757. ")
  11758. (defvar org-todo-statistics-hook nil
  11759. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11760. This hook runs even if there is no statistics cookie present, in which case
  11761. `org-after-todo-statistics-hook' would not run.")
  11762. (defun org-todo-trigger-tag-changes (state)
  11763. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11764. (let ((l org-todo-state-tags-triggers)
  11765. changes)
  11766. (when (or (not state) (equal state ""))
  11767. (setq changes (append changes (cdr (assoc "" l)))))
  11768. (when (and (stringp state) (> (length state) 0))
  11769. (setq changes (append changes (cdr (assoc state l)))))
  11770. (when (member state org-not-done-keywords)
  11771. (setq changes (append changes (cdr (assoc 'todo l)))))
  11772. (when (member state org-done-keywords)
  11773. (setq changes (append changes (cdr (assoc 'done l)))))
  11774. (dolist (c changes)
  11775. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11776. (defun org-local-logging (value)
  11777. "Get logging settings from a property VALUE."
  11778. ;; Directly set the variables, they are already local.
  11779. (setq org-log-done nil
  11780. org-log-repeat nil
  11781. org-todo-log-states nil)
  11782. (dolist (w (org-split-string value))
  11783. (let (a)
  11784. (cond
  11785. ((setq a (assoc w org-startup-options))
  11786. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11787. (set (nth 1 a) (nth 2 a))))
  11788. ((setq a (org-extract-log-state-settings w))
  11789. (and (member (car a) org-todo-keywords-1)
  11790. (push a org-todo-log-states)))))))
  11791. (defun org-get-todo-sequence-head (kwd)
  11792. "Return the head of the TODO sequence to which KWD belongs.
  11793. If KWD is not set, check if there is a text property remembering the
  11794. right sequence."
  11795. (let (p)
  11796. (cond
  11797. ((not kwd)
  11798. (or (get-text-property (point-at-bol) 'org-todo-head)
  11799. (progn
  11800. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11801. nil (point-at-eol)))
  11802. (get-text-property p 'org-todo-head))))
  11803. ((not (member kwd org-todo-keywords-1))
  11804. (car org-todo-keywords-1))
  11805. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11806. (defun org-fast-todo-selection ()
  11807. "Fast TODO keyword selection with single keys.
  11808. Returns the new TODO keyword, or nil if no state change should occur."
  11809. (let* ((fulltable org-todo-key-alist)
  11810. (done-keywords org-done-keywords) ;; needed for the faces.
  11811. (maxlen (apply 'max (mapcar
  11812. (lambda (x)
  11813. (if (stringp (car x)) (string-width (car x)) 0))
  11814. fulltable)))
  11815. (expert nil)
  11816. (fwidth (+ maxlen 3 1 3))
  11817. (ncol (/ (- (window-width) 4) fwidth))
  11818. tg cnt e c tbl
  11819. groups ingroup)
  11820. (save-excursion
  11821. (save-window-excursion
  11822. (if expert
  11823. (set-buffer (get-buffer-create " *Org todo*"))
  11824. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11825. (erase-buffer)
  11826. (setq-local org-done-keywords done-keywords)
  11827. (setq tbl fulltable cnt 0)
  11828. (while (setq e (pop tbl))
  11829. (cond
  11830. ((equal e '(:startgroup))
  11831. (push '() groups) (setq ingroup t)
  11832. (unless (= cnt 0)
  11833. (setq cnt 0)
  11834. (insert "\n"))
  11835. (insert "{ "))
  11836. ((equal e '(:endgroup))
  11837. (setq ingroup nil cnt 0)
  11838. (insert "}\n"))
  11839. ((equal e '(:newline))
  11840. (unless (= cnt 0)
  11841. (setq cnt 0)
  11842. (insert "\n")
  11843. (setq e (car tbl))
  11844. (while (equal (car tbl) '(:newline))
  11845. (insert "\n")
  11846. (setq tbl (cdr tbl)))))
  11847. (t
  11848. (setq tg (car e) c (cdr e))
  11849. (when ingroup (push tg (car groups)))
  11850. (setq tg (org-add-props tg nil 'face
  11851. (org-get-todo-face tg)))
  11852. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11853. (insert "[" c "] " tg (make-string
  11854. (- fwidth 4 (length tg)) ?\ ))
  11855. (when (= (setq cnt (1+ cnt)) ncol)
  11856. (insert "\n")
  11857. (when ingroup (insert " "))
  11858. (setq cnt 0)))))
  11859. (insert "\n")
  11860. (goto-char (point-min))
  11861. (unless expert (org-fit-window-to-buffer))
  11862. (message "[a-z..]:Set [SPC]:clear")
  11863. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11864. (cond
  11865. ((or (= c ?\C-g)
  11866. (and (= c ?q) (not (rassoc c fulltable))))
  11867. (setq quit-flag t))
  11868. ((= c ?\ ) nil)
  11869. ((setq e (rassoc c fulltable) tg (car e))
  11870. tg)
  11871. (t (setq quit-flag t)))))))
  11872. (defun org-entry-is-todo-p ()
  11873. (member (org-get-todo-state) org-not-done-keywords))
  11874. (defun org-entry-is-done-p ()
  11875. (member (org-get-todo-state) org-done-keywords))
  11876. (defun org-get-todo-state ()
  11877. "Return the TODO keyword of the current subtree."
  11878. (save-excursion
  11879. (org-back-to-heading t)
  11880. (and (looking-at org-todo-line-regexp)
  11881. (match-end 2)
  11882. (match-string 2))))
  11883. (defun org-at-date-range-p (&optional inactive-ok)
  11884. "Non-nil if point is inside a date range.
  11885. When optional argument INACTIVE-OK is non-nil, also consider
  11886. inactive time ranges.
  11887. When this function returns a non-nil value, match data is set
  11888. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11889. on INACTIVE-OK."
  11890. (interactive)
  11891. (save-excursion
  11892. (catch 'exit
  11893. (let ((pos (point)))
  11894. (skip-chars-backward "^[<\r\n")
  11895. (skip-chars-backward "<[")
  11896. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11897. (>= (match-end 0) pos)
  11898. (throw 'exit t))
  11899. (skip-chars-backward "^<[\r\n")
  11900. (skip-chars-backward "<[")
  11901. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11902. (>= (match-end 0) pos)
  11903. (throw 'exit t)))
  11904. nil)))
  11905. (defun org-get-repeat (&optional tagline)
  11906. "Check if there is a deadline/schedule with repeater in this entry."
  11907. (save-match-data
  11908. (save-excursion
  11909. (org-back-to-heading t)
  11910. (and (re-search-forward (if tagline
  11911. (concat tagline "\\s-*" org-repeat-re)
  11912. org-repeat-re)
  11913. (org-entry-end-position) t)
  11914. (match-string-no-properties 1)))))
  11915. (defvar org-last-changed-timestamp)
  11916. (defvar org-last-inserted-timestamp)
  11917. (defvar org-log-post-message)
  11918. (defvar org-log-note-purpose)
  11919. (defvar org-log-note-how nil)
  11920. (defvar org-log-note-extra)
  11921. (defun org-auto-repeat-maybe (done-word)
  11922. "Check if the current headline contains a repeated deadline/schedule.
  11923. If yes, set TODO state back to what it was and change the base date
  11924. of repeating deadline/scheduled time stamps to new date.
  11925. This function is run automatically after each state change to a DONE state."
  11926. ;; last-state is dynamically scoped into this function
  11927. (let* ((repeat (org-get-repeat))
  11928. (aa (assoc org-last-state org-todo-kwd-alist))
  11929. (interpret (nth 1 aa))
  11930. (head (nth 2 aa))
  11931. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11932. (msg "Entry repeats: ")
  11933. (org-log-done nil)
  11934. (org-todo-log-states nil)
  11935. re type n what ts time to-state)
  11936. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11937. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11938. (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
  11939. org-todo-repeat-to-state))
  11940. (unless (and to-state (member to-state org-todo-keywords-1))
  11941. (setq to-state (if (eq interpret 'type) org-last-state head)))
  11942. (org-todo to-state)
  11943. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  11944. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11945. (org-time-stamp-format t t))))
  11946. (when org-log-repeat
  11947. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11948. (memq 'org-add-log-note post-command-hook))
  11949. ;; OK, we are already setup for some record
  11950. (when (eq org-log-repeat 'note)
  11951. ;; make sure we take a note, not only a time stamp
  11952. (setq org-log-note-how 'note))
  11953. ;; Set up for taking a record
  11954. (org-add-log-setup 'state (or done-word (car org-done-keywords))
  11955. org-last-state
  11956. 'findpos org-log-repeat)))
  11957. (org-back-to-heading t)
  11958. (org-add-planning-info nil nil 'closed)
  11959. (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11960. org-deadline-time-regexp "\\)\\|\\("
  11961. org-ts-regexp "\\)"))
  11962. (while (re-search-forward
  11963. re (save-excursion (outline-next-heading) (point)) t)
  11964. (setq type (if (match-end 1) org-scheduled-string
  11965. (if (match-end 3) org-deadline-string "Plain:"))
  11966. ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
  11967. (if (not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  11968. (org-remove-timestamp-with-keyword org-scheduled-string)
  11969. (setq n (string-to-number (match-string 2 ts))
  11970. what (match-string 3 ts))
  11971. (when (equal what "w") (setq n (* n 7) what "d"))
  11972. (when (and (equal what "h")
  11973. (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
  11974. (user-error
  11975. "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
  11976. ;; Preparation, see if we need to modify the start date for the change
  11977. (when (match-end 1)
  11978. (setq time (save-match-data (org-time-string-to-time ts)))
  11979. (cond
  11980. ((equal (match-string 1 ts) ".")
  11981. ;; Shift starting date to today
  11982. (org-timestamp-change
  11983. (- (org-today) (time-to-days time))
  11984. 'day))
  11985. ((equal (match-string 1 ts) "+")
  11986. (let ((nshiftmax 10) (nshift 0))
  11987. (while (or (= nshift 0)
  11988. (<= (time-to-days time)
  11989. (time-to-days (current-time))))
  11990. (when (= (incf nshift) nshiftmax)
  11991. (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
  11992. (user-error "Abort")))
  11993. (org-timestamp-change n (cdr (assoc what whata)))
  11994. (org-at-timestamp-p t)
  11995. (setq ts (match-string 1))
  11996. (setq time (save-match-data (org-time-string-to-time ts)))))
  11997. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11998. ;; rematch, so that we have everything in place for the real shift
  11999. (org-at-timestamp-p t)
  12000. (setq ts (match-string 1))
  12001. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
  12002. (save-excursion
  12003. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12004. (setq msg (concat msg type " " org-last-changed-timestamp " "))))
  12005. (setq org-log-post-message msg)
  12006. (message "%s" msg))))
  12007. (defun org-show-todo-tree (arg)
  12008. "Make a compact tree which shows all headlines marked with TODO.
  12009. The tree will show the lines where the regexp matches, and all higher
  12010. headlines above the match.
  12011. With a \\[universal-argument] prefix, prompt for a regexp to match.
  12012. With a numeric prefix N, construct a sparse tree for the Nth element
  12013. of `org-todo-keywords-1'."
  12014. (interactive "P")
  12015. (let ((case-fold-search nil)
  12016. (kwd-re
  12017. (cond ((null arg) org-not-done-regexp)
  12018. ((equal arg '(4))
  12019. (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
  12020. (mapcar 'list org-todo-keywords-1))))
  12021. (concat "\\("
  12022. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12023. "\\)\\>")))
  12024. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12025. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12026. org-todo-keywords-1)))
  12027. (t (user-error "Invalid prefix argument: %s" arg)))))
  12028. (message "%d TODO entries found"
  12029. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12030. (defun org-deadline (arg &optional time)
  12031. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12032. With one universal prefix argument, remove any deadline from the item.
  12033. With two universal prefix arguments, prompt for a warning delay.
  12034. With argument TIME, set the deadline at the corresponding date. TIME
  12035. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12036. (interactive "P")
  12037. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12038. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12039. 'region-start-level 'region))
  12040. org-loop-over-headlines-in-active-region)
  12041. (org-map-entries
  12042. `(org-deadline ',arg ,time)
  12043. org-loop-over-headlines-in-active-region
  12044. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12045. (let* ((old-date (org-entry-get nil "DEADLINE"))
  12046. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12047. (repeater (and old-date
  12048. (string-match
  12049. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12050. old-date)
  12051. (match-string 1 old-date))))
  12052. (cond
  12053. ((equal arg '(4))
  12054. (when (and old-date org-log-redeadline)
  12055. (org-add-log-setup 'deldeadline nil old-date 'findpos
  12056. org-log-redeadline))
  12057. (org-remove-timestamp-with-keyword org-deadline-string)
  12058. (message "Item no longer has a deadline."))
  12059. ((equal arg '(16))
  12060. (save-excursion
  12061. (org-back-to-heading t)
  12062. (if (re-search-forward
  12063. org-deadline-time-regexp
  12064. (save-excursion (outline-next-heading) (point)) t)
  12065. (let* ((rpl0 (match-string 1))
  12066. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12067. (replace-match
  12068. (concat org-deadline-string
  12069. " <" rpl
  12070. (format " -%dd"
  12071. (abs
  12072. (- (time-to-days
  12073. (save-match-data
  12074. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12075. (time-to-days old-date-time))))
  12076. ">") t t))
  12077. (user-error "No deadline information to update"))))
  12078. (t
  12079. (org-add-planning-info 'deadline time 'closed)
  12080. (when (and old-date
  12081. org-log-redeadline
  12082. (not (equal old-date org-last-inserted-timestamp)))
  12083. (org-add-log-setup
  12084. 'redeadline org-last-inserted-timestamp old-date 'findpos
  12085. org-log-redeadline))
  12086. (when repeater
  12087. (save-excursion
  12088. (org-back-to-heading t)
  12089. (when (re-search-forward (concat org-deadline-string " "
  12090. org-last-inserted-timestamp)
  12091. (save-excursion
  12092. (outline-next-heading) (point)) t)
  12093. (goto-char (1- (match-end 0)))
  12094. (insert " " repeater)
  12095. (setq org-last-inserted-timestamp
  12096. (concat (substring org-last-inserted-timestamp 0 -1)
  12097. " " repeater
  12098. (substring org-last-inserted-timestamp -1))))))
  12099. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12100. (defun org-schedule (arg &optional time)
  12101. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12102. With one universal prefix argument, remove any scheduling date from the item.
  12103. With two universal prefix arguments, prompt for a delay cookie.
  12104. With argument TIME, scheduled at the corresponding date. TIME can
  12105. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12106. (interactive "P")
  12107. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12108. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12109. 'region-start-level 'region))
  12110. org-loop-over-headlines-in-active-region)
  12111. (org-map-entries
  12112. `(org-schedule ',arg ,time)
  12113. org-loop-over-headlines-in-active-region
  12114. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12115. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12116. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12117. (repeater (and old-date
  12118. (string-match
  12119. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12120. old-date)
  12121. (match-string 1 old-date))))
  12122. (cond
  12123. ((equal arg '(4))
  12124. (progn
  12125. (when (and old-date org-log-reschedule)
  12126. (org-add-log-setup 'delschedule nil old-date 'findpos
  12127. org-log-reschedule))
  12128. (org-remove-timestamp-with-keyword org-scheduled-string)
  12129. (message "Item is no longer scheduled.")))
  12130. ((equal arg '(16))
  12131. (save-excursion
  12132. (org-back-to-heading t)
  12133. (if (re-search-forward
  12134. org-scheduled-time-regexp
  12135. (save-excursion (outline-next-heading) (point)) t)
  12136. (let* ((rpl0 (match-string 1))
  12137. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12138. (replace-match
  12139. (concat org-scheduled-string
  12140. " <" rpl
  12141. (format " -%dd"
  12142. (abs
  12143. (- (time-to-days
  12144. (save-match-data
  12145. (org-read-date nil t nil "Delay until" old-date-time)))
  12146. (time-to-days old-date-time))))
  12147. ">") t t))
  12148. (user-error "No scheduled information to update"))))
  12149. (t
  12150. (org-add-planning-info 'scheduled time 'closed)
  12151. (when (and old-date
  12152. org-log-reschedule
  12153. (not (equal old-date org-last-inserted-timestamp)))
  12154. (org-add-log-setup
  12155. 'reschedule org-last-inserted-timestamp old-date 'findpos
  12156. org-log-reschedule))
  12157. (when repeater
  12158. (save-excursion
  12159. (org-back-to-heading t)
  12160. (when (re-search-forward (concat org-scheduled-string " "
  12161. org-last-inserted-timestamp)
  12162. (save-excursion
  12163. (outline-next-heading) (point)) t)
  12164. (goto-char (1- (match-end 0)))
  12165. (insert " " repeater)
  12166. (setq org-last-inserted-timestamp
  12167. (concat (substring org-last-inserted-timestamp 0 -1)
  12168. " " repeater
  12169. (substring org-last-inserted-timestamp -1))))))
  12170. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12171. (defun org-get-scheduled-time (pom &optional inherit)
  12172. "Get the scheduled time as a time tuple, of a format suitable
  12173. for calling org-schedule with, or if there is no scheduling,
  12174. returns nil."
  12175. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12176. (when time
  12177. (apply 'encode-time (org-parse-time-string time)))))
  12178. (defun org-get-deadline-time (pom &optional inherit)
  12179. "Get the deadline as a time tuple, of a format suitable for
  12180. calling org-deadline with, or if there is no scheduling, returns
  12181. nil."
  12182. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12183. (when time
  12184. (apply 'encode-time (org-parse-time-string time)))))
  12185. (defun org-remove-timestamp-with-keyword (keyword)
  12186. "Remove all time stamps with KEYWORD in the current entry."
  12187. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12188. beg)
  12189. (save-excursion
  12190. (org-back-to-heading t)
  12191. (setq beg (point))
  12192. (outline-next-heading)
  12193. (while (re-search-backward re beg t)
  12194. (replace-match "")
  12195. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12196. (equal (char-before) ?\ ))
  12197. (backward-delete-char 1)
  12198. (when (string-match "^[ \t]*$" (buffer-substring
  12199. (point-at-bol) (point-at-eol)))
  12200. (delete-region (point-at-bol)
  12201. (min (point-max) (1+ (point-at-eol))))))))))
  12202. (defvar org-time-was-given) ; dynamically scoped parameter
  12203. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12204. (defun org-at-planning-p ()
  12205. "Non-nil when point is on a planning info line."
  12206. ;; This is as accurate and faster than `org-element-at-point' since
  12207. ;; planning info location is fixed in the section.
  12208. (org-with-wide-buffer
  12209. (beginning-of-line)
  12210. (and (org-looking-at-p org-planning-line-re)
  12211. (eq (point)
  12212. (ignore-errors
  12213. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12214. (org-back-to-heading t)
  12215. (org-with-limited-levels (org-back-to-heading t)))
  12216. (line-beginning-position 2))))))
  12217. (defun org-add-planning-info (what &optional time &rest remove)
  12218. "Insert new timestamp with keyword in the planning line.
  12219. WHAT indicates what kind of time stamp to add. It is a symbol
  12220. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12221. the time to use. If none is given, the user is prompted for
  12222. a date. REMOVE indicates what kind of entries to remove. An old
  12223. WHAT entry will also be removed."
  12224. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12225. (catch 'exit
  12226. (when (and (memq what '(scheduled deadline))
  12227. (or (not time)
  12228. (and (stringp time)
  12229. (string-match "^[-+]+[0-9]" time))))
  12230. ;; Try to get a default date/time from existing timestamp
  12231. (save-excursion
  12232. (org-back-to-heading t)
  12233. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12234. (when (re-search-forward (if (eq what 'scheduled)
  12235. org-scheduled-time-regexp
  12236. org-deadline-time-regexp)
  12237. end t)
  12238. (setq ts (match-string 1)
  12239. default-time (apply 'encode-time (org-parse-time-string ts))
  12240. default-input (and ts (org-get-compact-tod ts)))))))
  12241. (when what
  12242. (setq time
  12243. (if (stringp time)
  12244. ;; This is a string (relative or absolute), set
  12245. ;; proper date.
  12246. (apply #'encode-time
  12247. (org-read-date-analyze
  12248. time default-time (decode-time default-time)))
  12249. ;; If necessary, get the time from the user
  12250. (or time (org-read-date nil 'to-time nil nil
  12251. default-time default-input)))))
  12252. (org-with-wide-buffer
  12253. (org-back-to-heading t)
  12254. (forward-line)
  12255. (unless (bolp) (insert "\n"))
  12256. (cond ((org-looking-at-p org-planning-line-re)
  12257. ;; Move to current indentation.
  12258. (skip-chars-forward " \t")
  12259. ;; Check if we have to remove something.
  12260. (dolist (type (if what (cons what remove) remove))
  12261. (save-excursion
  12262. (when (re-search-forward
  12263. (case type
  12264. (closed org-closed-time-regexp)
  12265. (deadline org-deadline-time-regexp)
  12266. (scheduled org-scheduled-time-regexp)
  12267. (otherwise
  12268. (error "Invalid planning type: %s" type)))
  12269. (line-end-position) t)
  12270. ;; Delete until next keyword or end of line.
  12271. (delete-region
  12272. (match-beginning 0)
  12273. (if (re-search-forward org-keyword-time-not-clock-regexp
  12274. (line-end-position)
  12275. t)
  12276. (match-beginning 0)
  12277. (line-end-position))))))
  12278. ;; If there is nothing more to add and no more keyword
  12279. ;; is left, remove the line completely.
  12280. (if (and (org-looking-at-p "[ \t]*$") (not what))
  12281. (delete-region (line-beginning-position)
  12282. (line-beginning-position 2))
  12283. ;; If we removed last keyword, do not leave trailing
  12284. ;; white space at the end of line.
  12285. (let ((p (point)))
  12286. (save-excursion
  12287. (end-of-line)
  12288. (unless (= (skip-chars-backward " \t" p) 0)
  12289. (delete-region (point) (line-end-position)))))))
  12290. ((not what) (throw 'exit nil)) ; Nothing to do.
  12291. (t (insert-before-markers "\n")
  12292. (backward-char 1)
  12293. (when org-adapt-indentation
  12294. (org-indent-to-column (1+ (org-outline-level))))))
  12295. (when what
  12296. ;; Insert planning keyword.
  12297. (insert (case what
  12298. (closed org-closed-string)
  12299. (deadline org-deadline-string)
  12300. (scheduled org-scheduled-string)
  12301. (otherwise (error "Invalid planning type: %s" what)))
  12302. " ")
  12303. ;; Insert associated timestamp.
  12304. (let ((ts (org-insert-time-stamp
  12305. time
  12306. (or org-time-was-given
  12307. (and (eq what 'closed) org-log-done-with-time))
  12308. (eq what 'closed)
  12309. nil nil (list org-end-time-was-given))))
  12310. (unless (eolp) (insert " "))
  12311. ts))))))
  12312. (defvar org-log-note-marker (make-marker))
  12313. (defvar org-log-note-purpose nil)
  12314. (defvar org-log-note-state nil)
  12315. (defvar org-log-note-previous-state nil)
  12316. (defvar org-log-note-extra nil)
  12317. (defvar org-log-note-window-configuration nil)
  12318. (defvar org-log-note-return-to (make-marker))
  12319. (defvar org-log-note-effective-time nil
  12320. "Remembered current time so that dynamically scoped
  12321. `org-extend-today-until' affects tha timestamps in state change
  12322. log")
  12323. (defvar org-log-post-message nil
  12324. "Message to be displayed after a log note has been stored.
  12325. The auto-repeater uses this.")
  12326. (defun org-add-note ()
  12327. "Add a note to the current entry.
  12328. This is done in the same way as adding a state change note."
  12329. (interactive)
  12330. (org-add-log-setup 'note nil nil 'findpos nil))
  12331. (defun org-log-beginning (&optional create)
  12332. "Return expected start of log notes in current entry.
  12333. When optional argument CREATE is non-nil, the function creates
  12334. a drawer to store notes, if necessary. Returned position ignores
  12335. narrowing."
  12336. (org-with-wide-buffer
  12337. (org-end-of-meta-data)
  12338. (let ((end (if (org-at-heading-p) (point)
  12339. (save-excursion (outline-next-heading) (point))))
  12340. (drawer (org-log-into-drawer)))
  12341. (cond
  12342. (drawer
  12343. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12344. (case-fold-search t))
  12345. (catch 'exit
  12346. ;; Try to find existing drawer.
  12347. (while (re-search-forward regexp end t)
  12348. (let ((element (org-element-at-point)))
  12349. (when (eq (org-element-type element) 'drawer)
  12350. (let ((cend (org-element-property :contents-end element)))
  12351. (when (and (not org-log-states-order-reversed) cend)
  12352. (goto-char cend)))
  12353. (throw 'exit nil))))
  12354. ;; No drawer found. Create one, if permitted.
  12355. (when create
  12356. (unless (bolp) (insert "\n"))
  12357. (let ((beg (point)))
  12358. (insert ":" drawer ":\n:END:\n")
  12359. (org-indent-region beg (point)))
  12360. (end-of-line -1)))))
  12361. (org-log-state-notes-insert-after-drawers
  12362. (while (and (looking-at org-drawer-regexp)
  12363. (progn (goto-char (match-end 0))
  12364. (re-search-forward org-property-end-re end t)))
  12365. (forward-line)))))
  12366. (if (bolp) (point) (line-beginning-position 2))))
  12367. (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
  12368. "Set up the post command hook to take a note.
  12369. If this is about to TODO state change, the new state is expected in STATE.
  12370. When FINDPOS is non-nil, find the correct position for the note in
  12371. the current entry. If not, assume that it can be inserted at point.
  12372. HOW is an indicator what kind of note should be created.
  12373. EXTRA is additional text that will be inserted into the notes buffer."
  12374. (org-with-wide-buffer
  12375. (when findpos
  12376. (goto-char (org-log-beginning t))
  12377. (unless org-log-states-order-reversed
  12378. (org-skip-over-state-notes)
  12379. (skip-chars-backward " \t\n\r")
  12380. (forward-line)))
  12381. (move-marker org-log-note-marker (point))
  12382. ;; Preserve position even if a property drawer is inserted in the
  12383. ;; process.
  12384. (set-marker-insertion-type org-log-note-marker t)
  12385. (setq org-log-note-purpose purpose
  12386. org-log-note-state state
  12387. org-log-note-previous-state prev-state
  12388. org-log-note-how how
  12389. org-log-note-extra extra
  12390. org-log-note-effective-time (org-current-effective-time))
  12391. (add-hook 'post-command-hook 'org-add-log-note 'append)))
  12392. (defun org-skip-over-state-notes ()
  12393. "Skip past the list of State notes in an entry."
  12394. (when (ignore-errors (goto-char (org-in-item-p)))
  12395. (let* ((struct (org-list-struct))
  12396. (prevs (org-list-prevs-alist struct))
  12397. (regexp
  12398. (concat "[ \t]*- +"
  12399. (replace-regexp-in-string
  12400. " +" " +"
  12401. (org-replace-escapes
  12402. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12403. `(("%d" . ,org-ts-regexp-inactive)
  12404. ("%D" . ,org-ts-regexp)
  12405. ("%s" . "\"\\S-+\"")
  12406. ("%S" . "\"\\S-+\"")
  12407. ("%t" . ,org-ts-regexp-inactive)
  12408. ("%T" . ,org-ts-regexp)
  12409. ("%u" . ".*?")
  12410. ("%U" . ".*?")))))))
  12411. (while (org-looking-at-p regexp)
  12412. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12413. (org-list-get-item-end (point) struct)))))))
  12414. (defun org-add-log-note (&optional purpose)
  12415. "Pop up a window for taking a note, and add this note later at point."
  12416. (remove-hook 'post-command-hook 'org-add-log-note)
  12417. (setq org-log-note-window-configuration (current-window-configuration))
  12418. (delete-other-windows)
  12419. (move-marker org-log-note-return-to (point))
  12420. (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12421. (goto-char org-log-note-marker)
  12422. (org-switch-to-buffer-other-window "*Org Note*")
  12423. (erase-buffer)
  12424. (if (memq org-log-note-how '(time state))
  12425. (let (current-prefix-arg) (org-store-log-note))
  12426. (let ((org-inhibit-startup t)) (org-mode))
  12427. (insert (format "# Insert note for %s.
  12428. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12429. (cond
  12430. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12431. ((eq org-log-note-purpose 'done) "closed todo item")
  12432. ((eq org-log-note-purpose 'state)
  12433. (format "state change from \"%s\" to \"%s\""
  12434. (or org-log-note-previous-state "")
  12435. (or org-log-note-state "")))
  12436. ((eq org-log-note-purpose 'reschedule)
  12437. "rescheduling")
  12438. ((eq org-log-note-purpose 'delschedule)
  12439. "no longer scheduled")
  12440. ((eq org-log-note-purpose 'redeadline)
  12441. "changing deadline")
  12442. ((eq org-log-note-purpose 'deldeadline)
  12443. "removing deadline")
  12444. ((eq org-log-note-purpose 'refile)
  12445. "refiling")
  12446. ((eq org-log-note-purpose 'note)
  12447. "this entry")
  12448. (t (error "This should not happen")))))
  12449. (when org-log-note-extra (insert org-log-note-extra))
  12450. (setq-local org-finish-function 'org-store-log-note)
  12451. (run-hooks 'org-log-buffer-setup-hook)))
  12452. (defvar org-note-abort nil) ; dynamically scoped
  12453. (defun org-store-log-note ()
  12454. "Finish taking a log note, and insert it to where it belongs."
  12455. (let ((txt (buffer-string)))
  12456. (kill-buffer (current-buffer))
  12457. (let ((note (cdr (assq org-log-note-purpose org-log-note-headings))) lines)
  12458. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12459. (setq txt (replace-match "" t t txt)))
  12460. (when (string-match "\\s-+\\'" txt)
  12461. (setq txt (replace-match "" t t txt)))
  12462. (setq lines (org-split-string txt "\n"))
  12463. (when (and note (string-match "\\S-" note))
  12464. (setq note
  12465. (org-replace-escapes
  12466. note
  12467. (list (cons "%u" (user-login-name))
  12468. (cons "%U" user-full-name)
  12469. (cons "%t" (format-time-string
  12470. (org-time-stamp-format 'long 'inactive)
  12471. org-log-note-effective-time))
  12472. (cons "%T" (format-time-string
  12473. (org-time-stamp-format 'long nil)
  12474. org-log-note-effective-time))
  12475. (cons "%d" (format-time-string
  12476. (org-time-stamp-format nil 'inactive)
  12477. org-log-note-effective-time))
  12478. (cons "%D" (format-time-string
  12479. (org-time-stamp-format nil nil)
  12480. org-log-note-effective-time))
  12481. (cons "%s" (cond
  12482. ((not org-log-note-state) "")
  12483. ((org-string-match-p org-ts-regexp
  12484. org-log-note-state)
  12485. (format "\"[%s]\""
  12486. (substring org-log-note-state 1 -1)))
  12487. (t (format "\"%s\"" org-log-note-state))))
  12488. (cons "%S"
  12489. (cond
  12490. ((not org-log-note-previous-state) "")
  12491. ((org-string-match-p org-ts-regexp
  12492. org-log-note-previous-state)
  12493. (format "\"[%s]\""
  12494. (substring
  12495. org-log-note-previous-state 1 -1)))
  12496. (t (format "\"%s\""
  12497. org-log-note-previous-state)))))))
  12498. (when lines (setq note (concat note " \\\\")))
  12499. (push note lines))
  12500. (when (or current-prefix-arg org-note-abort)
  12501. (when (org-log-into-drawer)
  12502. (org-remove-empty-drawer-at org-log-note-marker))
  12503. (setq lines nil))
  12504. (when lines
  12505. (with-current-buffer (marker-buffer org-log-note-marker)
  12506. (org-with-wide-buffer
  12507. (goto-char org-log-note-marker)
  12508. (move-marker org-log-note-marker nil)
  12509. ;; Make sure point is at the beginning of an empty line.
  12510. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12511. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12512. ;; In an existing list, add a new item at the top level.
  12513. ;; Otherwise, indent line like a regular one.
  12514. (let ((itemp (org-in-item-p)))
  12515. (if itemp
  12516. (org-indent-line-to
  12517. (let ((struct (save-excursion
  12518. (goto-char itemp) (org-list-struct))))
  12519. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12520. (org-indent-line)))
  12521. (insert (org-list-bullet-string "-") (pop lines))
  12522. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12523. (dolist (line lines)
  12524. (insert "\n")
  12525. (org-indent-line-to ind)
  12526. (insert line)))
  12527. (message "Note stored")
  12528. (org-back-to-heading t)
  12529. (org-cycle-hide-drawers 'children))
  12530. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12531. ;; from within `org-add-log-note' because `buffer-undo-list'
  12532. ;; is then modified outside of `org-with-remote-undo'.
  12533. (when (eq this-command 'org-agenda-todo)
  12534. (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
  12535. ;; Don't add undo information when called from `org-agenda-todo'
  12536. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12537. (set-window-configuration org-log-note-window-configuration)
  12538. (with-current-buffer (marker-buffer org-log-note-return-to)
  12539. (goto-char org-log-note-return-to))
  12540. (move-marker org-log-note-return-to nil)
  12541. (and org-log-post-message (message "%s" org-log-post-message))))
  12542. (defun org-remove-empty-drawer-at (pos)
  12543. "Remove an empty drawer at position POS.
  12544. POS may also be a marker."
  12545. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12546. (org-with-wide-buffer
  12547. (goto-char pos)
  12548. (let ((drawer (org-element-at-point)))
  12549. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12550. (not (org-element-property :contents-begin drawer)))
  12551. (delete-region (org-element-property :begin drawer)
  12552. (progn (goto-char (org-element-property :end drawer))
  12553. (skip-chars-backward " \r\t\n")
  12554. (forward-line)
  12555. (point))))))))
  12556. (defvar org-ts-type nil)
  12557. (defun org-sparse-tree (&optional arg type)
  12558. "Create a sparse tree, prompt for the details.
  12559. This command can create sparse trees. You first need to select the type
  12560. of match used to create the tree:
  12561. t Show all TODO entries.
  12562. T Show entries with a specific TODO keyword.
  12563. m Show entries selected by a tags/property match.
  12564. p Enter a property name and its value (both with completion on existing
  12565. names/values) and show entries with that property.
  12566. r Show entries matching a regular expression (`/' can be used as well).
  12567. b Show deadlines and scheduled items before a date.
  12568. a Show deadlines and scheduled items after a date.
  12569. d Show deadlines due within `org-deadline-warning-days'.
  12570. D Show deadlines and scheduled items between a date range."
  12571. (interactive "P")
  12572. (setq type (or type org-sparse-tree-default-date-type))
  12573. (setq org-ts-type type)
  12574. (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12575. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  12576. [c]ycle through date types: %s"
  12577. (case type
  12578. (all "all timestamps")
  12579. (scheduled "only scheduled")
  12580. (deadline "only deadline")
  12581. (active "only active timestamps")
  12582. (inactive "only inactive timestamps")
  12583. (closed "with a closed time-stamp")
  12584. (otherwise "scheduled/deadline")))
  12585. (let ((answer (read-char-exclusive)))
  12586. (case answer
  12587. (?c
  12588. (org-sparse-tree
  12589. arg
  12590. (cadr
  12591. (memq type '(nil all scheduled deadline active inactive closed)))))
  12592. (?d (call-interactively 'org-check-deadlines))
  12593. (?b (call-interactively 'org-check-before-date))
  12594. (?a (call-interactively 'org-check-after-date))
  12595. (?D (call-interactively 'org-check-dates-range))
  12596. (?t (call-interactively 'org-show-todo-tree))
  12597. (?T (org-show-todo-tree '(4)))
  12598. (?m (call-interactively 'org-match-sparse-tree))
  12599. ((?p ?P)
  12600. (let* ((kwd (org-icompleting-read
  12601. "Property: " (mapcar 'list (org-buffer-property-keys))))
  12602. (value (org-icompleting-read
  12603. "Value: " (mapcar 'list (org-property-values kwd)))))
  12604. (unless (string-match "\\`{.*}\\'" value)
  12605. (setq value (concat "\"" value "\"")))
  12606. (org-match-sparse-tree arg (concat kwd "=" value))))
  12607. ((?r ?R ?/) (call-interactively 'org-occur))
  12608. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12609. (defvar-local org-occur-highlights nil
  12610. "List of overlays used for occur matches.")
  12611. (defvar-local org-occur-parameters nil
  12612. "Parameters of the active org-occur calls.
  12613. This is a list, each call to org-occur pushes as cons cell,
  12614. containing the regular expression and the callback, onto the list.
  12615. The list can contain several entries if `org-occur' has been called
  12616. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12617. will only contain one set of parameters. When the highlights are
  12618. removed (for example with `C-c C-c', or with the next edit (depending
  12619. on `org-remove-highlights-with-change'), this variable is emptied
  12620. as well.")
  12621. (defun org-occur (regexp &optional keep-previous callback)
  12622. "Make a compact tree which shows all matches of REGEXP.
  12623. The tree will show the lines where the regexp matches, and all higher
  12624. headlines above the match. It will also show the heading after the match,
  12625. to make sure editing the matching entry is easy.
  12626. If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
  12627. call to `org-occur' will be kept, to allow stacking of calls to this
  12628. command.
  12629. If CALLBACK is non-nil, it is a function which is called to confirm
  12630. that the match should indeed be shown."
  12631. (interactive "sRegexp: \nP")
  12632. (when (equal regexp "")
  12633. (user-error "Regexp cannot be empty"))
  12634. (unless keep-previous
  12635. (org-remove-occur-highlights nil nil t))
  12636. (push (cons regexp callback) org-occur-parameters)
  12637. (let ((cnt 0))
  12638. (save-excursion
  12639. (goto-char (point-min))
  12640. (when (or (not keep-previous) ; do not want to keep
  12641. (not org-occur-highlights)) ; no previous matches
  12642. ;; hide everything
  12643. (org-overview))
  12644. (while (re-search-forward regexp nil t)
  12645. (backward-char) ;; FIXME: Match timestamps at the end of a headline
  12646. (when (or (not callback)
  12647. (save-match-data (funcall callback)))
  12648. (setq cnt (1+ cnt))
  12649. (when org-highlight-sparse-tree-matches
  12650. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12651. (org-show-context 'occur-tree))))
  12652. (when org-remove-highlights-with-change
  12653. (org-add-hook 'before-change-functions 'org-remove-occur-highlights
  12654. nil 'local))
  12655. (unless org-sparse-tree-open-archived-trees
  12656. (org-hide-archived-subtrees (point-min) (point-max)))
  12657. (run-hooks 'org-occur-hook)
  12658. (when (org-called-interactively-p 'interactive)
  12659. (message "%d match(es) for regexp %s" cnt regexp))
  12660. cnt))
  12661. (defun org-occur-next-match (&optional n reset)
  12662. "Function for `next-error-function' to find sparse tree matches.
  12663. N is the number of matches to move, when negative move backwards.
  12664. RESET is entirely ignored - this function always goes back to the
  12665. starting point when no match is found."
  12666. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12667. (search-func (if (< n 0)
  12668. 'previous-single-char-property-change
  12669. 'next-single-char-property-change))
  12670. (n (abs n))
  12671. (pos (point))
  12672. p1)
  12673. (catch 'exit
  12674. (while (setq p1 (funcall search-func (point) 'org-type))
  12675. (when (equal p1 limit)
  12676. (goto-char pos)
  12677. (user-error "No more matches"))
  12678. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12679. (setq n (1- n))
  12680. (when (= n 0)
  12681. (goto-char p1)
  12682. (throw 'exit (point))))
  12683. (goto-char p1))
  12684. (goto-char p1)
  12685. (user-error "No more matches"))))
  12686. (defun org-show-context (&optional key)
  12687. "Make sure point and context are visible.
  12688. Optional argument KEY, when non-nil, is a symbol. See
  12689. `org-show-context-detail' for allowed values and how much is to
  12690. be shown."
  12691. (org-show-set-visibility
  12692. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12693. ((cdr (assq key org-show-context-detail)))
  12694. (t (cdr (assq 'default org-show-context-detail))))))
  12695. (defun org-show-set-visibility (detail)
  12696. "Set visibility around point according to DETAIL.
  12697. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12698. `tree', `canonical' or t. See `org-show-context-detail' for more
  12699. information."
  12700. (unless (org-before-first-heading-p)
  12701. ;; Show current heading and possibly its entry, following headline
  12702. ;; or all children.
  12703. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12704. (org-flag-heading nil)
  12705. (org-show-entry)
  12706. (org-with-limited-levels
  12707. (case detail
  12708. ((tree canonical t) (org-show-children))
  12709. ((nil minimal ancestors))
  12710. (t (save-excursion
  12711. (outline-next-heading)
  12712. (org-flag-heading nil))))))
  12713. ;; Show all siblings.
  12714. (when (eq detail 'lineage) (org-show-siblings))
  12715. ;; Show ancestors, possibly with their children.
  12716. (when (memq detail '(ancestors lineage tree canonical t))
  12717. (save-excursion
  12718. (while (org-up-heading-safe)
  12719. (org-flag-heading nil)
  12720. (when (memq detail '(canonical t)) (org-show-entry))
  12721. (when (memq detail '(tree canonical t)) (org-show-children)))))))
  12722. (defvar org-reveal-start-hook nil
  12723. "Hook run before revealing a location.")
  12724. (defun org-reveal (&optional siblings)
  12725. "Show current entry, hierarchy above it, and the following headline.
  12726. This can be used to show a consistent set of context around
  12727. locations exposed with `org-show-context'.
  12728. With optional argument SIBLINGS, on each level of the hierarchy all
  12729. siblings are shown. This repairs the tree structure to what it would
  12730. look like when opened with hierarchical calls to `org-cycle'.
  12731. With double optional argument \\[universal-argument] \\[universal-argument], \
  12732. go to the parent and show the
  12733. entire tree."
  12734. (interactive "P")
  12735. (run-hooks 'org-reveal-start-hook)
  12736. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12737. ((equal siblings '(16))
  12738. (save-excursion
  12739. (when (org-up-heading-safe)
  12740. (org-show-subtree)
  12741. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12742. (t (org-show-set-visibility 'lineage))))
  12743. (defun org-highlight-new-match (beg end)
  12744. "Highlight from BEG to END and mark the highlight is an occur headline."
  12745. (let ((ov (make-overlay beg end)))
  12746. (overlay-put ov 'face 'secondary-selection)
  12747. (overlay-put ov 'org-type 'org-occur)
  12748. (push ov org-occur-highlights)))
  12749. (defun org-remove-occur-highlights (&optional beg end noremove)
  12750. "Remove the occur highlights from the buffer.
  12751. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12752. from the `before-change-functions' in the current buffer."
  12753. (interactive)
  12754. (unless org-inhibit-highlight-removal
  12755. (mapc 'delete-overlay org-occur-highlights)
  12756. (setq org-occur-highlights nil)
  12757. (setq org-occur-parameters nil)
  12758. (unless noremove
  12759. (remove-hook 'before-change-functions
  12760. 'org-remove-occur-highlights 'local))))
  12761. ;;;; Priorities
  12762. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12763. "Regular expression matching the priority indicator.")
  12764. (defvar org-remove-priority-next-time nil)
  12765. (defun org-priority-up ()
  12766. "Increase the priority of the current item."
  12767. (interactive)
  12768. (org-priority 'up))
  12769. (defun org-priority-down ()
  12770. "Decrease the priority of the current item."
  12771. (interactive)
  12772. (org-priority 'down))
  12773. (defun org-priority (&optional action show)
  12774. "Change the priority of an item.
  12775. ACTION can be `set', `up', `down', or a character."
  12776. (interactive "P")
  12777. (if (equal action '(4))
  12778. (org-show-priority)
  12779. (unless org-enable-priority-commands
  12780. (user-error "Priority commands are disabled"))
  12781. (setq action (or action 'set))
  12782. (let (current new news have remove)
  12783. (save-excursion
  12784. (org-back-to-heading t)
  12785. (when (looking-at org-priority-regexp)
  12786. (setq current (string-to-char (match-string 2))
  12787. have t))
  12788. (cond
  12789. ((eq action 'remove)
  12790. (setq remove t new ?\ ))
  12791. ((or (eq action 'set)
  12792. (if (featurep 'xemacs) (characterp action) (integerp action)))
  12793. (if (not (eq action 'set))
  12794. (setq new action)
  12795. (message "Priority %c-%c, SPC to remove: "
  12796. org-highest-priority org-lowest-priority)
  12797. (save-match-data
  12798. (setq new (read-char-exclusive))))
  12799. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12800. (= (upcase org-lowest-priority) org-lowest-priority))
  12801. (setq new (upcase new)))
  12802. (cond ((equal new ?\ ) (setq remove t))
  12803. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12804. (user-error "Priority must be between `%c' and `%c'"
  12805. org-highest-priority org-lowest-priority))))
  12806. ((eq action 'up)
  12807. (setq new (if have
  12808. (1- current) ; normal cycling
  12809. ;; last priority was empty
  12810. (if (eq last-command this-command)
  12811. org-lowest-priority ; wrap around empty to lowest
  12812. ;; default
  12813. (if org-priority-start-cycle-with-default
  12814. org-default-priority
  12815. (1- org-default-priority))))))
  12816. ((eq action 'down)
  12817. (setq new (if have
  12818. (1+ current) ; normal cycling
  12819. ;; last priority was empty
  12820. (if (eq last-command this-command)
  12821. org-highest-priority ; wrap around empty to highest
  12822. ;; default
  12823. (if org-priority-start-cycle-with-default
  12824. org-default-priority
  12825. (1+ org-default-priority))))))
  12826. (t (user-error "Invalid action")))
  12827. (when (or (< (upcase new) org-highest-priority)
  12828. (> (upcase new) org-lowest-priority))
  12829. (if (and (memq action '(up down))
  12830. (not have) (not (eq last-command this-command)))
  12831. ;; `new' is from default priority
  12832. (error
  12833. "The default can not be set, see `org-default-priority' why")
  12834. ;; normal cycling: `new' is beyond highest/lowest priority
  12835. ;; and is wrapped around to the empty priority
  12836. (setq remove t)))
  12837. (setq news (format "%c" new))
  12838. (if have
  12839. (if remove
  12840. (replace-match "" t t nil 1)
  12841. (replace-match news t t nil 2))
  12842. (if remove
  12843. (user-error "No priority cookie found in line")
  12844. (let ((case-fold-search nil))
  12845. (looking-at org-todo-line-regexp))
  12846. (if (match-end 2)
  12847. (progn
  12848. (goto-char (match-end 2))
  12849. (insert " [#" news "]"))
  12850. (goto-char (match-beginning 3))
  12851. (insert "[#" news "] "))))
  12852. (org-set-tags nil 'align))
  12853. (if remove
  12854. (message "Priority removed")
  12855. (message "Priority of current item set to %s" news)))))
  12856. (defun org-show-priority ()
  12857. "Show the priority of the current item.
  12858. This priority is composed of the main priority given with the [#A] cookies,
  12859. and by additional input from the age of a schedules or deadline entry."
  12860. (interactive)
  12861. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12862. (org-get-at-bol 'priority)
  12863. (save-excursion
  12864. (save-match-data
  12865. (beginning-of-line)
  12866. (and (looking-at org-heading-regexp)
  12867. (org-get-priority (match-string 0))))))))
  12868. (message "Priority is %d" (if pri pri -1000))))
  12869. (defun org-get-priority (s)
  12870. "Find priority cookie and return priority."
  12871. (save-match-data
  12872. (if (functionp org-get-priority-function)
  12873. (funcall org-get-priority-function)
  12874. (if (not (string-match org-priority-regexp s))
  12875. (* 1000 (- org-lowest-priority org-default-priority))
  12876. (* 1000 (- org-lowest-priority
  12877. (string-to-char (match-string 2 s))))))))
  12878. ;;;; Tags
  12879. (defvar org-agenda-archives-mode)
  12880. (defvar org-map-continue-from nil
  12881. "Position from where mapping should continue.
  12882. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12883. (defvar org-scanner-tags nil
  12884. "The current tag list while the tags scanner is running.")
  12885. (defvar org-trust-scanner-tags nil
  12886. "Should `org-get-tags-at' use the tags for the scanner.
  12887. This is for internal dynamical scoping only.
  12888. When this is non-nil, the function `org-get-tags-at' will return the value
  12889. of `org-scanner-tags' instead of building the list by itself. This
  12890. can lead to large speed-ups when the tags scanner is used in a file with
  12891. many entries, and when the list of tags is retrieved, for example to
  12892. obtain a list of properties. Building the tags list for each entry in such
  12893. a file becomes an N^2 operation - but with this variable set, it scales
  12894. as N.")
  12895. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12896. "Scan headline tags with inheritance and produce output ACTION.
  12897. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12898. or `agenda' to produce an entry list for an agenda view. It can also be
  12899. a Lisp form or a function that should be called at each matched headline, in
  12900. this case the return value is a list of all return values from these calls.
  12901. MATCHER is a Lisp form to be evaluated, testing if a given set of tags
  12902. qualifies a headline for inclusion. When TODO-ONLY is non-nil,
  12903. only lines with a not-done TODO keyword are included in the output.
  12904. This should be the same variable that was scoped into
  12905. and set by `org-make-tags-matcher' when it constructed MATCHER.
  12906. START-LEVEL can be a string with asterisks, reducing the scope to
  12907. headlines matching this string."
  12908. (require 'org-agenda)
  12909. (let* ((re (concat "^"
  12910. (if start-level
  12911. ;; Get the correct level to match
  12912. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12913. org-outline-regexp)
  12914. " *\\(\\<\\("
  12915. (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
  12916. (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
  12917. (props (list 'face 'default
  12918. 'done-face 'org-agenda-done
  12919. 'undone-face 'default
  12920. 'mouse-face 'highlight
  12921. 'org-not-done-regexp org-not-done-regexp
  12922. 'org-todo-regexp org-todo-regexp
  12923. 'org-complex-heading-regexp org-complex-heading-regexp
  12924. 'help-echo
  12925. (format "mouse-2 or RET jump to org file %s"
  12926. (abbreviate-file-name
  12927. (or (buffer-file-name (buffer-base-buffer))
  12928. (buffer-name (buffer-base-buffer)))))))
  12929. (org-map-continue-from nil)
  12930. lspos tags tags-list
  12931. (tags-alist (list (cons 0 org-file-tags)))
  12932. (llast 0) rtn rtn1 level category i txt
  12933. todo marker entry priority
  12934. ts-date ts-date-type ts-date-pair)
  12935. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12936. (setq action (list 'lambda nil action)))
  12937. (save-excursion
  12938. (goto-char (point-min))
  12939. (when (eq action 'sparse-tree)
  12940. (org-overview)
  12941. (org-remove-occur-highlights))
  12942. (while (let (case-fold-search)
  12943. (re-search-forward re nil t))
  12944. (setq org-map-continue-from nil)
  12945. (catch :skip
  12946. (setq todo
  12947. ;; TODO: is the 1-2 difference a bug?
  12948. (when (match-end 1) (org-match-string-no-properties 2))
  12949. tags (when (match-end 4) (org-match-string-no-properties 4)))
  12950. (goto-char (setq lspos (match-beginning 0)))
  12951. (setq level (org-reduced-level (org-outline-level))
  12952. category (org-get-category))
  12953. (when (eq action 'agenda)
  12954. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12955. ts-date (car ts-date-pair)
  12956. ts-date-type (cdr ts-date-pair)))
  12957. (setq i llast llast level)
  12958. ;; remove tag lists from same and sublevels
  12959. (while (>= i level)
  12960. (when (setq entry (assoc i tags-alist))
  12961. (setq tags-alist (delete entry tags-alist)))
  12962. (setq i (1- i)))
  12963. ;; add the next tags
  12964. (when tags
  12965. (setq tags (org-split-string tags ":")
  12966. tags-alist
  12967. (cons (cons level tags) tags-alist)))
  12968. ;; compile tags for current headline
  12969. (setq tags-list
  12970. (if org-use-tag-inheritance
  12971. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12972. tags)
  12973. org-scanner-tags tags-list)
  12974. (when org-use-tag-inheritance
  12975. (setcdr (car tags-alist)
  12976. (mapcar (lambda (x)
  12977. (setq x (copy-sequence x))
  12978. (org-add-prop-inherited x))
  12979. (cdar tags-alist))))
  12980. (when (and tags org-use-tag-inheritance
  12981. (or (not (eq t org-use-tag-inheritance))
  12982. org-tags-exclude-from-inheritance))
  12983. ;; selective inheritance, remove uninherited ones
  12984. (setcdr (car tags-alist)
  12985. (org-remove-uninherited-tags (cdar tags-alist))))
  12986. (when (and
  12987. ;; eval matcher only when the todo condition is OK
  12988. (and (or (not todo-only) (member todo org-not-done-keywords))
  12989. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12990. (eval matcher)))
  12991. ;; Call the skipper, but return t if it does not skip,
  12992. ;; so that the `and' form continues evaluating
  12993. (progn
  12994. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12995. t)
  12996. ;; Check if timestamps are deselecting this entry
  12997. (or (not todo-only)
  12998. (and (member todo org-not-done-keywords)
  12999. (or (not org-agenda-tags-todo-honor-ignore-options)
  13000. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13001. ;; select this headline
  13002. (cond
  13003. ((eq action 'sparse-tree)
  13004. (and org-highlight-sparse-tree-matches
  13005. (org-get-heading) (match-end 0)
  13006. (org-highlight-new-match
  13007. (match-beginning 1) (match-end 1)))
  13008. (org-show-context 'tags-tree))
  13009. ((eq action 'agenda)
  13010. (setq txt (org-agenda-format-item
  13011. ""
  13012. (concat
  13013. (if (eq org-tags-match-list-sublevels 'indented)
  13014. (make-string (1- level) ?.) "")
  13015. (org-get-heading))
  13016. (make-string level ?\s)
  13017. category
  13018. tags-list)
  13019. priority (org-get-priority txt))
  13020. (goto-char lspos)
  13021. (setq marker (org-agenda-new-marker))
  13022. (org-add-props txt props
  13023. 'org-marker marker 'org-hd-marker marker 'org-category category
  13024. 'todo-state todo
  13025. 'ts-date ts-date
  13026. 'priority priority
  13027. 'type (concat "tagsmatch" ts-date-type))
  13028. (push txt rtn))
  13029. ((functionp action)
  13030. (setq org-map-continue-from nil)
  13031. (save-excursion
  13032. (setq rtn1 (funcall action))
  13033. (push rtn1 rtn)))
  13034. (t (user-error "Invalid action")))
  13035. ;; if we are to skip sublevels, jump to end of subtree
  13036. (unless org-tags-match-list-sublevels
  13037. (org-end-of-subtree t)
  13038. (backward-char 1))))
  13039. ;; Get the correct position from where to continue
  13040. (if org-map-continue-from
  13041. (goto-char org-map-continue-from)
  13042. (and (= (point) lspos) (end-of-line 1)))))
  13043. (when (and (eq action 'sparse-tree)
  13044. (not org-sparse-tree-open-archived-trees))
  13045. (org-hide-archived-subtrees (point-min) (point-max)))
  13046. (nreverse rtn)))
  13047. (defun org-remove-uninherited-tags (tags)
  13048. "Remove all tags that are not inherited from the list TAGS."
  13049. (cond
  13050. ((eq org-use-tag-inheritance t)
  13051. (if org-tags-exclude-from-inheritance
  13052. (org-delete-all org-tags-exclude-from-inheritance tags)
  13053. tags))
  13054. ((not org-use-tag-inheritance) nil)
  13055. ((stringp org-use-tag-inheritance)
  13056. (delq nil (mapcar
  13057. (lambda (x)
  13058. (if (and (string-match org-use-tag-inheritance x)
  13059. (not (member x org-tags-exclude-from-inheritance)))
  13060. x nil))
  13061. tags)))
  13062. ((listp org-use-tag-inheritance)
  13063. (delq nil (mapcar
  13064. (lambda (x)
  13065. (if (member x org-use-tag-inheritance) x nil))
  13066. tags)))))
  13067. (defun org-match-sparse-tree (&optional todo-only match)
  13068. "Create a sparse tree according to tags string MATCH.
  13069. MATCH can contain positive and negative selection of tags, like
  13070. \"+WORK+URGENT-WITHBOSS\".
  13071. If optional argument TODO-ONLY is non-nil, only select lines that are
  13072. also TODO lines."
  13073. (interactive "P")
  13074. (org-agenda-prepare-buffers (list (current-buffer)))
  13075. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
  13076. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13077. (defvar org-cached-props nil)
  13078. (defun org-cached-entry-get (pom property)
  13079. (if (or (eq t org-use-property-inheritance)
  13080. (and (stringp org-use-property-inheritance)
  13081. (let ((case-fold-search t))
  13082. (org-string-match-p org-use-property-inheritance property)))
  13083. (and (listp org-use-property-inheritance)
  13084. (member-ignore-case property org-use-property-inheritance)))
  13085. ;; Caching is not possible, check it directly.
  13086. (org-entry-get pom property 'inherit)
  13087. ;; Get all properties, so we can do complicated checks easily.
  13088. (cdr (assoc-string property
  13089. (or org-cached-props
  13090. (setq org-cached-props (org-entry-properties pom)))
  13091. t))))
  13092. (defun org-global-tags-completion-table (&optional files)
  13093. "Return the list of all tags in all agenda buffer/files.
  13094. Optional FILES argument is a list of files which can be used
  13095. instead of the agenda files."
  13096. (save-excursion
  13097. (org-uniquify
  13098. (delq nil
  13099. (apply 'append
  13100. (mapcar
  13101. (lambda (file)
  13102. (set-buffer (find-file-noselect file))
  13103. (append (org-get-buffer-tags)
  13104. (mapcar (lambda (x) (if (stringp (car-safe x))
  13105. (list (car-safe x)) nil))
  13106. org-tag-alist)))
  13107. (if (and files (car files))
  13108. files
  13109. (org-agenda-files))))))))
  13110. (defun org-make-tags-matcher (match)
  13111. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13112. The variable `todo-only' is scoped dynamically into this function.
  13113. It will be set to t if the matcher restricts matching to TODO entries,
  13114. otherwise will not be touched.
  13115. Returns a cons of the selection string MATCH and the constructed
  13116. lisp form implementing the matcher. The matcher is to be evaluated
  13117. at an Org entry, with point on the headline, and returns t if the
  13118. entry matches the selection string MATCH. The returned lisp form
  13119. references two variables with information about the entry, which
  13120. must be bound around the form's evaluation: todo, the TODO keyword
  13121. at the entry (or nil of none); and tags-list, the list of all tags
  13122. at the entry including inherited ones. Additionally, the category
  13123. of the entry (if any) must be specified as the text property
  13124. `org-category' on the headline.
  13125. See also `org-scan-tags'.
  13126. "
  13127. (declare (special todo-only))
  13128. (unless (boundp 'todo-only)
  13129. (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
  13130. (unless match
  13131. ;; Get a new match request, with completion against the global
  13132. ;; tags table and the local tags in current buffer
  13133. (let ((org-last-tags-completion-table
  13134. (org-uniquify
  13135. (delq nil (append (org-get-buffer-tags)
  13136. (org-global-tags-completion-table))))))
  13137. (setq match (org-completing-read-no-i
  13138. "Match: " 'org-tags-completion-function nil nil nil
  13139. 'org-tags-history))))
  13140. ;; Parse the string and create a lisp form
  13141. (let ((match0 match)
  13142. (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
  13143. minus tag mm
  13144. tagsmatch todomatch tagsmatcher todomatcher kwd matcher
  13145. orterms term orlist re-p str-p level-p level-op time-p
  13146. prop-p pn pv po gv rest (start 0) (ss 0))
  13147. ;; Expand group tags
  13148. (setq match (org-tags-expand match))
  13149. ;; Check if there is a TODO part of this match, which would be the
  13150. ;; part after a "/". TO make sure that this slash is not part of
  13151. ;; a property value to be matched against, we also check that there
  13152. ;; is no " after that slash.
  13153. ;; First, find the last slash
  13154. (while (string-match "/+" match ss)
  13155. (setq start (match-beginning 0) ss (match-end 0)))
  13156. (if (and (string-match "/+" match start)
  13157. (not (save-match-data (string-match "\"" match start))))
  13158. ;; match contains also a todo-matching request
  13159. (progn
  13160. (setq tagsmatch (substring match 0 (match-beginning 0))
  13161. todomatch (substring match (match-end 0)))
  13162. (when (string-match "^!" todomatch)
  13163. (setq todo-only t todomatch (substring todomatch 1)))
  13164. (when (string-match "^\\s-*$" todomatch)
  13165. (setq todomatch nil)))
  13166. ;; only matching tags
  13167. (setq tagsmatch match todomatch nil))
  13168. ;; Make the tags matcher
  13169. (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
  13170. (setq tagsmatcher t)
  13171. (setq orterms (org-split-string tagsmatch "|") orlist nil)
  13172. (while (setq term (pop orterms))
  13173. (while (and (equal (substring term -1) "\\") orterms)
  13174. (setq term (concat term "|" (pop orterms)))) ; repair bad split
  13175. (while (string-match re term)
  13176. (setq rest (substring term (match-end 0))
  13177. minus (and (match-end 1)
  13178. (equal (match-string 1 term) "-"))
  13179. tag (save-match-data (replace-regexp-in-string
  13180. "\\\\-" "-"
  13181. (match-string 2 term)))
  13182. re-p (equal (string-to-char tag) ?{)
  13183. level-p (match-end 4)
  13184. prop-p (match-end 5)
  13185. mm (cond
  13186. (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13187. (level-p
  13188. (setq level-op (org-op-to-function (match-string 3 term)))
  13189. `(,level-op level ,(string-to-number
  13190. (match-string 4 term))))
  13191. (prop-p
  13192. (setq pn (match-string 5 term)
  13193. po (match-string 6 term)
  13194. pv (match-string 7 term)
  13195. re-p (equal (string-to-char pv) ?{)
  13196. str-p (equal (string-to-char pv) ?\")
  13197. time-p (save-match-data
  13198. (string-match "^\"[[<].*[]>]\"$" pv))
  13199. pv (if (or re-p str-p) (substring pv 1 -1) pv))
  13200. (when time-p (setq pv (org-matcher-time pv)))
  13201. (setq po (org-op-to-function po (if time-p 'time str-p)))
  13202. (cond
  13203. ((equal pn "CATEGORY")
  13204. (setq gv '(get-text-property (point) 'org-category)))
  13205. ((equal pn "TODO")
  13206. (setq gv 'todo))
  13207. (t
  13208. (setq gv `(org-cached-entry-get nil ,pn))))
  13209. (if re-p
  13210. (if (eq po 'org<>)
  13211. `(not (string-match ,pv (or ,gv "")))
  13212. `(string-match ,pv (or ,gv "")))
  13213. (if str-p
  13214. `(,po (or ,gv "") ,pv)
  13215. `(,po (string-to-number (or ,gv ""))
  13216. ,(string-to-number pv) ))))
  13217. (t `(member ,tag tags-list)))
  13218. mm (if minus (list 'not mm) mm)
  13219. term rest)
  13220. (push mm tagsmatcher))
  13221. (push (if (> (length tagsmatcher) 1)
  13222. (cons 'and tagsmatcher)
  13223. (car tagsmatcher))
  13224. orlist)
  13225. (setq tagsmatcher nil))
  13226. (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
  13227. (setq tagsmatcher
  13228. (list 'progn '(setq org-cached-props nil) tagsmatcher)))
  13229. ;; Make the todo matcher
  13230. (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
  13231. (setq todomatcher t)
  13232. (setq orterms (org-split-string todomatch "|") orlist nil)
  13233. (dolist (term orterms)
  13234. (while (string-match re term)
  13235. (setq minus (and (match-end 1)
  13236. (equal (match-string 1 term) "-"))
  13237. kwd (match-string 2 term)
  13238. re-p (equal (string-to-char kwd) ?{)
  13239. term (substring term (match-end 0))
  13240. mm (if re-p
  13241. `(string-match ,(substring kwd 1 -1) todo)
  13242. (list 'equal 'todo kwd))
  13243. mm (if minus (list 'not mm) mm))
  13244. (push mm todomatcher))
  13245. (push (if (> (length todomatcher) 1)
  13246. (cons 'and todomatcher)
  13247. (car todomatcher))
  13248. orlist)
  13249. (setq todomatcher nil))
  13250. (setq todomatcher (if (> (length orlist) 1)
  13251. (cons 'or orlist) (car orlist))))
  13252. ;; Return the string and lisp forms of the matcher
  13253. (setq matcher (if todomatcher
  13254. (list 'and tagsmatcher todomatcher)
  13255. tagsmatcher))
  13256. (when todo-only
  13257. (setq matcher (list 'and '(member todo org-not-done-keywords)
  13258. matcher)))
  13259. (cons match0 matcher)))
  13260. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13261. "Expand group tags in MATCH.
  13262. This replaces every group tag in MATCH with a regexp tag search.
  13263. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13264. will be replaced like this:
  13265. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13266. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13267. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13268. Replacing by a regexp preserves the structure of the match.
  13269. E.g., this expansion
  13270. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13271. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13272. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13273. A group tag in MATCH can contain regular expressions of its own.
  13274. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13275. will be replaced like this:
  13276. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13277. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13278. assumed to be a single group tag, and the function will return
  13279. the list of tags in this group.
  13280. When DOWNCASE is non-nil, expand downcased TAGS."
  13281. (if org-group-tags
  13282. (let* ((case-fold-search t)
  13283. (stable org-mode-syntax-table)
  13284. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13285. (taggroups (if downcased
  13286. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13287. taggroups)
  13288. taggroups))
  13289. (taggroups-keys (mapcar #'car taggroups))
  13290. (return-match (if downcased (downcase match) match))
  13291. (count 0)
  13292. (work-already-expanded tags-already-expanded)
  13293. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13294. ;; @ and _ are allowed as word-components in tags.
  13295. (modify-syntax-entry ?@ "w" stable)
  13296. (modify-syntax-entry ?_ "w" stable)
  13297. ;; Temporarily replace regexp-expressions in the match-expression.
  13298. (while (string-match "{.+?}" return-match)
  13299. (incf count)
  13300. (push (match-string 0 return-match) regexps-in-match)
  13301. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13302. (while (and taggroups-keys
  13303. (with-syntax-table stable
  13304. (string-match
  13305. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13306. (regexp-opt taggroups-keys) "\\>\\)")
  13307. return-match)))
  13308. (let* ((dir (match-string 1 return-match))
  13309. (tag (match-string 2 return-match))
  13310. (tag (if downcased (downcase tag) tag)))
  13311. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13312. (member tag work-already-expanded))
  13313. (setq tags-in-group (assoc tag taggroups))
  13314. (push tag work-already-expanded)
  13315. ;; Recursively expand each tag in the group, if the tag hasn't
  13316. ;; already been expanded. Restore the match-data after all recursive calls.
  13317. (save-match-data
  13318. (let (tags-expanded)
  13319. (dolist (x (cdr tags-in-group))
  13320. (if (and (member x taggroups-keys)
  13321. (not (member x work-already-expanded)))
  13322. (setq tags-expanded
  13323. (delete-dups
  13324. (append
  13325. (org-tags-expand x t downcased
  13326. work-already-expanded)
  13327. tags-expanded)))
  13328. (setq tags-expanded
  13329. (append (list x) tags-expanded)))
  13330. (setq work-already-expanded
  13331. (delete-dups
  13332. (append tags-expanded
  13333. work-already-expanded))))
  13334. (setq tags-in-group
  13335. (delete-dups (cons (car tags-in-group)
  13336. tags-expanded)))))
  13337. ;; Filter tag-regexps from tags.
  13338. (setq regexp-in-group-escaped
  13339. (delq nil (mapcar (lambda (x)
  13340. (if (stringp x)
  13341. (and (equal "{" (substring x 0 1))
  13342. (equal "}" (substring x -1))
  13343. x)
  13344. x))
  13345. tags-in-group))
  13346. regexp-in-group
  13347. (mapcar (lambda (x)
  13348. (substring x 1 -1))
  13349. regexp-in-group-escaped)
  13350. tags-in-group
  13351. (delq nil (mapcar (lambda (x)
  13352. (if (stringp x)
  13353. (and (not (equal "{" (substring x 0 1)))
  13354. (not (equal "}" (substring x -1)))
  13355. x)
  13356. x))
  13357. tags-in-group)))
  13358. ;; If single-as-list, do no more in the while-loop.
  13359. (if (not single-as-list)
  13360. (progn
  13361. (when regexp-in-group
  13362. (setq regexp-in-group
  13363. (concat "\\|"
  13364. (mapconcat 'identity regexp-in-group
  13365. "\\|"))))
  13366. (setq tags-in-group
  13367. (concat dir
  13368. "{\\<"
  13369. (regexp-opt tags-in-group)
  13370. "\\>"
  13371. regexp-in-group
  13372. "}"))
  13373. (when (stringp tags-in-group)
  13374. (org-add-props tags-in-group '(grouptag t)))
  13375. (setq return-match
  13376. (replace-match tags-in-group t t return-match)))
  13377. (setq tags-in-group
  13378. (append regexp-in-group-escaped tags-in-group))))
  13379. (setq taggroups-keys (delete tag taggroups-keys))))
  13380. ;; Add the regular expressions back into the match-expression again.
  13381. (while regexps-in-match
  13382. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13383. (pop regexps-in-match)
  13384. return-match t t))
  13385. (decf count))
  13386. (if single-as-list
  13387. (if tags-in-group tags-in-group (list return-match))
  13388. return-match))
  13389. (if single-as-list
  13390. (list (if downcased (downcase match) match))
  13391. match)))
  13392. (defun org-op-to-function (op &optional stringp)
  13393. "Turn an operator into the appropriate function."
  13394. (setq op
  13395. (cond
  13396. ((equal op "<" ) '(< string< org-time<))
  13397. ((equal op ">" ) '(> org-string> org-time>))
  13398. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13399. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13400. ((member op '("=" "==")) '(= string= org-time=))
  13401. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13402. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13403. (defun org<> (a b) (not (= a b)))
  13404. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13405. (defun org-string>= (a b) (not (string< a b)))
  13406. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13407. (defun org-string<> (a b) (not (string= a b)))
  13408. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13409. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13410. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13411. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13412. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13413. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13414. (defun org-2ft (s)
  13415. "Convert S to a floating point time.
  13416. If S is already a number, just return it. If it is a string, parse
  13417. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13418. (cond
  13419. ((numberp s) s)
  13420. ((stringp s)
  13421. (condition-case nil
  13422. (float-time (apply 'encode-time (org-parse-time-string s)))
  13423. (error 0.)))
  13424. (t 0.)))
  13425. (defun org-time-today ()
  13426. "Time in seconds today at 0:00.
  13427. Returns the float number of seconds since the beginning of the
  13428. epoch to the beginning of today (00:00)."
  13429. (float-time (apply 'encode-time
  13430. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13431. (defun org-matcher-time (s)
  13432. "Interpret a time comparison value."
  13433. (save-match-data
  13434. (cond
  13435. ((string= s "<now>") (float-time))
  13436. ((string= s "<today>") (org-time-today))
  13437. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13438. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13439. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13440. (+ (org-time-today)
  13441. (* (string-to-number (match-string 1 s))
  13442. (cdr (assoc (match-string 2 s)
  13443. '(("d" . 86400.0) ("w" . 604800.0)
  13444. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13445. (t (org-2ft s)))))
  13446. (defun org-match-any-p (re list)
  13447. "Does re match any element of list?"
  13448. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13449. (delq nil list))
  13450. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13451. (defvar org-tags-overlay (make-overlay 1 1))
  13452. (org-detach-overlay org-tags-overlay)
  13453. (defun org-get-local-tags-at (&optional pos)
  13454. "Get a list of tags defined in the current headline."
  13455. (org-get-tags-at pos 'local))
  13456. (defun org-get-local-tags ()
  13457. "Get a list of tags defined in the current headline."
  13458. (org-get-tags-at nil 'local))
  13459. (defun org-get-tags-at (&optional pos local)
  13460. "Get a list of all headline tags applicable at POS.
  13461. POS defaults to point. If tags are inherited, the list contains
  13462. the targets in the same sequence as the headlines appear, i.e.
  13463. the tags of the current headline come last.
  13464. When LOCAL is non-nil, only return tags from the current headline,
  13465. ignore inherited ones."
  13466. (interactive)
  13467. (if (and org-trust-scanner-tags
  13468. (or (not pos) (equal pos (point)))
  13469. (not local))
  13470. org-scanner-tags
  13471. (let (tags ltags lastpos parent)
  13472. (save-excursion
  13473. (save-restriction
  13474. (widen)
  13475. (goto-char (or pos (point)))
  13476. (save-match-data
  13477. (catch 'done
  13478. (condition-case nil
  13479. (progn
  13480. (org-back-to-heading t)
  13481. (while (not (equal lastpos (point)))
  13482. (setq lastpos (point))
  13483. (when (looking-at
  13484. (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13485. (setq ltags (org-split-string
  13486. (org-match-string-no-properties 1) ":"))
  13487. (when parent
  13488. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13489. (setq tags (append
  13490. (if parent
  13491. (org-remove-uninherited-tags ltags)
  13492. ltags)
  13493. tags)))
  13494. (or org-use-tag-inheritance (throw 'done t))
  13495. (when local (throw 'done t))
  13496. (or (org-up-heading-safe) (error nil))
  13497. (setq parent t)))
  13498. (error nil)))))
  13499. (if local
  13500. tags
  13501. (reverse (delete-dups
  13502. (reverse (append
  13503. (org-remove-uninherited-tags
  13504. org-file-tags)
  13505. tags)))))))))
  13506. (defun org-add-prop-inherited (s)
  13507. (add-text-properties 0 (length s) '(inherited t) s)
  13508. s)
  13509. (defun org-toggle-tag (tag &optional onoff)
  13510. "Toggle the tag TAG for the current line.
  13511. If ONOFF is `on' or `off', don't toggle but set to this state."
  13512. (let (res current)
  13513. (save-excursion
  13514. (org-back-to-heading t)
  13515. (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13516. (point-at-eol) t)
  13517. (progn
  13518. (setq current (match-string 1))
  13519. (replace-match ""))
  13520. (setq current ""))
  13521. (setq current (nreverse (org-split-string current ":")))
  13522. (cond
  13523. ((eq onoff 'on)
  13524. (setq res t)
  13525. (or (member tag current) (push tag current)))
  13526. ((eq onoff 'off)
  13527. (or (not (member tag current)) (setq current (delete tag current))))
  13528. (t (if (member tag current)
  13529. (setq current (delete tag current))
  13530. (setq res t)
  13531. (push tag current))))
  13532. (end-of-line 1)
  13533. (if current
  13534. (progn
  13535. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13536. (org-set-tags nil t))
  13537. (delete-horizontal-space))
  13538. (run-hooks 'org-after-tags-change-hook))
  13539. res))
  13540. (defun org-align-tags-here (to-col)
  13541. ;; Assumes that this is a headline
  13542. "Align tags on the current headline to TO-COL."
  13543. (let ((pos (point)) (col (current-column)) ncol tags-l p)
  13544. (beginning-of-line 1)
  13545. (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13546. (< pos (match-beginning 2)))
  13547. (progn
  13548. (setq tags-l (- (match-end 2) (match-beginning 2)))
  13549. (goto-char (match-beginning 1))
  13550. (insert " ")
  13551. (delete-region (point) (1+ (match-beginning 2)))
  13552. (setq ncol (max (current-column)
  13553. (1+ col)
  13554. (if (> to-col 0)
  13555. to-col
  13556. (- (abs to-col) tags-l))))
  13557. (setq p (point))
  13558. (insert (make-string (- ncol (current-column)) ?\ ))
  13559. (setq ncol (current-column))
  13560. (when indent-tabs-mode (tabify p (point-at-eol)))
  13561. (org-move-to-column (min ncol col)))
  13562. (goto-char pos))))
  13563. (defun org-set-tags-command (&optional arg just-align)
  13564. "Call the set-tags command for the current entry."
  13565. (interactive "P")
  13566. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13567. (org-set-tags arg just-align)
  13568. (save-excursion
  13569. (unless (and (org-region-active-p)
  13570. org-loop-over-headlines-in-active-region)
  13571. (org-back-to-heading t))
  13572. (org-set-tags arg just-align))))
  13573. (defun org-set-tags-to (data)
  13574. "Set the tags of the current entry to DATA, replacing the current tags.
  13575. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13576. If DATA is nil or the empty string, any tags will be removed."
  13577. (interactive "sTags: ")
  13578. (setq data
  13579. (cond
  13580. ((eq data nil) "")
  13581. ((equal data "") "")
  13582. ((stringp data)
  13583. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13584. ":"))
  13585. ((listp data)
  13586. (concat ":" (mapconcat 'identity data ":") ":"))))
  13587. (when data
  13588. (save-excursion
  13589. (org-back-to-heading t)
  13590. (when (looking-at org-complex-heading-regexp)
  13591. (if (match-end 5)
  13592. (progn
  13593. (goto-char (match-beginning 5))
  13594. (insert data)
  13595. (delete-region (point) (point-at-eol))
  13596. (org-set-tags nil 'align))
  13597. (goto-char (point-at-eol))
  13598. (insert " " data)
  13599. (org-set-tags nil 'align)))
  13600. (beginning-of-line 1)
  13601. (when (looking-at ".*?\\([ \t]+\\)$")
  13602. (delete-region (match-beginning 1) (match-end 1))))))
  13603. (defun org-align-all-tags ()
  13604. "Align the tags i all headings."
  13605. (interactive)
  13606. (save-excursion
  13607. (or (ignore-errors (org-back-to-heading t))
  13608. (outline-next-heading))
  13609. (if (org-at-heading-p)
  13610. (org-set-tags t)
  13611. (message "No headings"))))
  13612. (defvar org-indent-indentation-per-level)
  13613. (defun org-set-tags (&optional arg just-align)
  13614. "Set the tags for the current headline.
  13615. With prefix ARG, realign all tags in headings in the current buffer.
  13616. When JUST-ALIGN is non-nil, only align tags."
  13617. (interactive "P")
  13618. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13619. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13620. 'region-start-level
  13621. 'region))
  13622. org-loop-over-headlines-in-active-region)
  13623. (org-map-entries
  13624. ;; We don't use ARG and JUST-ALIGN here because these args
  13625. ;; are not useful when looping over headlines.
  13626. #'org-set-tags
  13627. org-loop-over-headlines-in-active-region
  13628. cl
  13629. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13630. (let ((org-setting-tags t))
  13631. (if arg
  13632. (save-excursion
  13633. (goto-char (point-min))
  13634. (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
  13635. (while (re-search-forward org-outline-regexp-bol nil t)
  13636. (org-set-tags nil t)
  13637. (end-of-line)))
  13638. (message "All tags realigned to column %d" org-tags-column))
  13639. (let* ((current (org-get-tags-string))
  13640. (col (current-column))
  13641. (tags
  13642. (if just-align current
  13643. ;; Get a new set of tags from the user.
  13644. (save-excursion
  13645. (let* ((table
  13646. (setq
  13647. org-last-tags-completion-table
  13648. (append
  13649. org-tag-persistent-alist
  13650. (or org-tag-alist (org-get-buffer-tags))
  13651. (and
  13652. org-complete-tags-always-offer-all-agenda-tags
  13653. (org-global-tags-completion-table
  13654. (org-agenda-files))))))
  13655. (current-tags (org-split-string current ":"))
  13656. (inherited-tags
  13657. (nreverse (nthcdr (length current-tags)
  13658. (nreverse (org-get-tags-at))))))
  13659. (replace-regexp-in-string
  13660. "\\([-+&]+\\|,\\)"
  13661. ":"
  13662. (if (or (eq t org-use-fast-tag-selection)
  13663. (and org-use-fast-tag-selection
  13664. (delq nil (mapcar #'cdr table))))
  13665. (org-fast-tag-selection
  13666. current-tags inherited-tags table
  13667. (and org-fast-tag-selection-include-todo
  13668. org-todo-key-alist))
  13669. (let ((org-add-colon-after-tag-completion
  13670. (< 1 (length table))))
  13671. (org-trim
  13672. (completing-read
  13673. "Tags: "
  13674. #'org-tags-completion-function
  13675. nil nil current 'org-tags-history))))))))))
  13676. (when org-tags-sort-function
  13677. (setq tags
  13678. (mapconcat
  13679. #'identity
  13680. (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
  13681. org-tags-sort-function)
  13682. ":")))
  13683. (if (not (org-string-nw-p tags)) (setq tags "")
  13684. (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
  13685. (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
  13686. ;; Insert new tags at the correct column
  13687. (beginning-of-line)
  13688. (let ((level (if (looking-at org-outline-regexp)
  13689. (- (match-end 0) (point) 1)
  13690. 1)))
  13691. (cond
  13692. ((and (equal current "") (equal tags "")))
  13693. ((re-search-forward
  13694. (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
  13695. (line-end-position)
  13696. t)
  13697. (if (equal tags "") (replace-match "" t t)
  13698. (goto-char (match-beginning 0))
  13699. (let* ((c0 (current-column))
  13700. ;; Compute offset for the case of org-indent-mode
  13701. ;; active.
  13702. (di (if (org-bound-and-true-p org-indent-mode)
  13703. (* (1- org-indent-indentation-per-level)
  13704. (1- level))
  13705. 0))
  13706. (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
  13707. (tc (+ org-tags-column
  13708. (if (> org-tags-column 0) (- di) di)))
  13709. (c1 (max (1+ c0)
  13710. (if (> tc 0) tc
  13711. (- (- tc) (string-width tags)))))
  13712. (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
  13713. (replace-match rpl t t)
  13714. (when (and (not (featurep 'xemacs)) indent-tabs-mode)
  13715. (tabify p0 (point))))))
  13716. (t (error "Tags alignment failed"))))
  13717. (org-move-to-column col))
  13718. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13719. (defun org-change-tag-in-region (beg end tag off)
  13720. "Add or remove TAG for each entry in the region.
  13721. This works in the agenda, and also in an org-mode buffer."
  13722. (interactive
  13723. (list (region-beginning) (region-end)
  13724. (let ((org-last-tags-completion-table
  13725. (if (derived-mode-p 'org-mode)
  13726. (org-uniquify
  13727. (delq nil (append (org-get-buffer-tags)
  13728. (org-global-tags-completion-table))))
  13729. (org-global-tags-completion-table))))
  13730. (org-icompleting-read
  13731. "Tag: " 'org-tags-completion-function nil nil nil
  13732. 'org-tags-history))
  13733. (progn
  13734. (message "[s]et or [r]emove? ")
  13735. (equal (read-char-exclusive) ?r))))
  13736. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13737. (let ((agendap (equal major-mode 'org-agenda-mode))
  13738. l1 l2 m buf pos newhead (cnt 0))
  13739. (goto-char end)
  13740. (setq l2 (1- (org-current-line)))
  13741. (goto-char beg)
  13742. (setq l1 (org-current-line))
  13743. (loop for l from l1 to l2 do
  13744. (org-goto-line l)
  13745. (setq m (get-text-property (point) 'org-hd-marker))
  13746. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13747. (and agendap m))
  13748. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13749. pos (if agendap m (point)))
  13750. (with-current-buffer buf
  13751. (save-excursion
  13752. (save-restriction
  13753. (goto-char pos)
  13754. (setq cnt (1+ cnt))
  13755. (org-toggle-tag tag (if off 'off 'on))
  13756. (setq newhead (org-get-heading)))))
  13757. (and agendap (org-agenda-change-all-lines newhead m))))
  13758. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13759. (defun org-tags-completion-function (string predicate &optional flag)
  13760. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13761. (confirm (lambda (x) (stringp (car x)))))
  13762. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13763. (setq s1 (match-string 1 string)
  13764. s2 (match-string 2 string))
  13765. (setq s1 "" s2 string))
  13766. (cond
  13767. ((eq flag nil)
  13768. ;; try completion
  13769. (setq rtn (try-completion s2 ctable confirm))
  13770. (when (stringp rtn)
  13771. (setq rtn
  13772. (concat s1 s2 (substring rtn (length s2))
  13773. (if (and org-add-colon-after-tag-completion
  13774. (assoc rtn ctable))
  13775. ":" ""))))
  13776. rtn)
  13777. ((eq flag t)
  13778. ;; all-completions
  13779. (all-completions s2 ctable confirm))
  13780. ((eq flag 'lambda)
  13781. ;; exact match?
  13782. (assoc s2 ctable)))))
  13783. (defun org-fast-tag-insert (kwd tags face &optional end)
  13784. "Insert KDW, and the TAGS, the latter with face FACE.
  13785. Also insert END."
  13786. (insert (format "%-12s" (concat kwd ":"))
  13787. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13788. (or end "")))
  13789. (defun org-fast-tag-show-exit (flag)
  13790. (save-excursion
  13791. (org-goto-line 3)
  13792. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13793. (replace-match ""))
  13794. (when flag
  13795. (end-of-line 1)
  13796. (org-move-to-column (- (window-width) 19) t)
  13797. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13798. (defun org-set-current-tags-overlay (current prefix)
  13799. "Add an overlay to CURRENT tag with PREFIX."
  13800. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13801. (if (featurep 'xemacs)
  13802. (org-overlay-display org-tags-overlay (concat prefix s)
  13803. 'secondary-selection)
  13804. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13805. (org-overlay-display org-tags-overlay (concat prefix s)))))
  13806. (defvar org-last-tag-selection-key nil)
  13807. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13808. "Fast tag selection with single keys.
  13809. CURRENT is the current list of tags in the headline, INHERITED is the
  13810. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13811. possibly with grouping information. TODO-TABLE is a similar table with
  13812. TODO keywords, should these have keys assigned to them.
  13813. If the keys are nil, a-z are automatically assigned.
  13814. Returns the new tags string, or nil to not change the current settings."
  13815. (let* ((fulltable (append table todo-table))
  13816. (maxlen (apply 'max (mapcar
  13817. (lambda (x)
  13818. (if (stringp (car x)) (string-width (car x)) 0))
  13819. fulltable)))
  13820. (buf (current-buffer))
  13821. (expert (eq org-fast-tag-selection-single-key 'expert))
  13822. (buffer-tags nil)
  13823. (fwidth (+ maxlen 3 1 3))
  13824. (ncol (/ (- (window-width) 4) fwidth))
  13825. (i-face 'org-done)
  13826. (c-face 'org-todo)
  13827. tg cnt e c char c1 c2 ntable tbl rtn
  13828. ov-start ov-end ov-prefix
  13829. (exit-after-next org-fast-tag-selection-single-key)
  13830. (done-keywords org-done-keywords)
  13831. groups ingroup intaggroup)
  13832. (save-excursion
  13833. (beginning-of-line 1)
  13834. (if (looking-at
  13835. (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13836. (setq ov-start (match-beginning 1)
  13837. ov-end (match-end 1)
  13838. ov-prefix "")
  13839. (setq ov-start (1- (point-at-eol))
  13840. ov-end (1+ ov-start))
  13841. (skip-chars-forward "^\n\r")
  13842. (setq ov-prefix
  13843. (concat
  13844. (buffer-substring (1- (point)) (point))
  13845. (if (> (current-column) org-tags-column)
  13846. " "
  13847. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13848. (move-overlay org-tags-overlay ov-start ov-end)
  13849. (save-window-excursion
  13850. (if expert
  13851. (set-buffer (get-buffer-create " *Org tags*"))
  13852. (delete-other-windows)
  13853. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13854. (org-switch-to-buffer-other-window " *Org tags*"))
  13855. (erase-buffer)
  13856. (setq-local org-done-keywords done-keywords)
  13857. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13858. (org-fast-tag-insert "Current" current c-face "\n\n")
  13859. (org-fast-tag-show-exit exit-after-next)
  13860. (org-set-current-tags-overlay current ov-prefix)
  13861. (setq tbl fulltable char ?a cnt 0)
  13862. (while (setq e (pop tbl))
  13863. (cond
  13864. ((eq (car e) :startgroup)
  13865. (push '() groups) (setq ingroup t)
  13866. (unless (zerop cnt)
  13867. (setq cnt 0)
  13868. (insert "\n"))
  13869. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13870. ((eq (car e) :endgroup)
  13871. (setq ingroup nil cnt 0)
  13872. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13873. ((eq (car e) :startgrouptag)
  13874. (setq intaggroup t)
  13875. (unless (zerop cnt)
  13876. (setq cnt 0)
  13877. (insert "\n"))
  13878. (insert "[ "))
  13879. ((eq (car e) :endgrouptag)
  13880. (setq intaggroup nil cnt 0)
  13881. (insert "]\n"))
  13882. ((equal e '(:newline))
  13883. (unless (zerop cnt)
  13884. (setq cnt 0)
  13885. (insert "\n")
  13886. (setq e (car tbl))
  13887. (while (equal (car tbl) '(:newline))
  13888. (insert "\n")
  13889. (setq tbl (cdr tbl)))))
  13890. ((equal e '(:grouptags)) (insert " : "))
  13891. (t
  13892. (setq tg (copy-sequence (car e)) c2 nil)
  13893. (if (cdr e)
  13894. (setq c (cdr e))
  13895. ;; automatically assign a character.
  13896. (setq c1 (string-to-char
  13897. (downcase (substring
  13898. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13899. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13900. (while (or (rassoc char ntable) (rassoc char table))
  13901. (setq char (1+ char)))
  13902. (setq c2 c1))
  13903. (setq c (or c2 char)))
  13904. (when ingroup (push tg (car groups)))
  13905. (setq tg (org-add-props tg nil 'face
  13906. (cond
  13907. ((not (assoc tg table))
  13908. (org-get-todo-face tg))
  13909. ((member tg current) c-face)
  13910. ((member tg inherited) i-face))))
  13911. (when (equal (caar tbl) :grouptags)
  13912. (org-add-props tg nil 'face 'org-tag-group))
  13913. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13914. (insert "[" c "] " tg (make-string
  13915. (- fwidth 4 (length tg)) ?\ ))
  13916. (push (cons tg c) ntable)
  13917. (when (= (incf cnt) ncol)
  13918. (insert "\n")
  13919. (when (or ingroup intaggroup) (insert " "))
  13920. (setq cnt 0)))))
  13921. (setq ntable (nreverse ntable))
  13922. (insert "\n")
  13923. (goto-char (point-min))
  13924. (unless expert (org-fit-window-to-buffer))
  13925. (setq rtn
  13926. (catch 'exit
  13927. (while t
  13928. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13929. (if (not groups) "no " "")
  13930. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13931. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13932. (setq org-last-tag-selection-key c)
  13933. (cond
  13934. ((= c ?\r) (throw 'exit t))
  13935. ((= c ?!)
  13936. (setq groups (not groups))
  13937. (goto-char (point-min))
  13938. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13939. ((= c ?\C-c)
  13940. (if (not expert)
  13941. (org-fast-tag-show-exit
  13942. (setq exit-after-next (not exit-after-next)))
  13943. (setq expert nil)
  13944. (delete-other-windows)
  13945. (set-window-buffer (split-window-vertically) " *Org tags*")
  13946. (org-switch-to-buffer-other-window " *Org tags*")
  13947. (org-fit-window-to-buffer)))
  13948. ((or (= c ?\C-g)
  13949. (and (= c ?q) (not (rassoc c ntable))))
  13950. (org-detach-overlay org-tags-overlay)
  13951. (setq quit-flag t))
  13952. ((= c ?\ )
  13953. (setq current nil)
  13954. (when exit-after-next (setq exit-after-next 'now)))
  13955. ((= c ?\t)
  13956. (condition-case nil
  13957. (setq tg (org-icompleting-read
  13958. "Tag: "
  13959. (or buffer-tags
  13960. (with-current-buffer buf
  13961. (setq buffer-tags
  13962. (org-get-buffer-tags))))))
  13963. (quit (setq tg "")))
  13964. (when (string-match "\\S-" tg)
  13965. (add-to-list 'buffer-tags (list tg))
  13966. (if (member tg current)
  13967. (setq current (delete tg current))
  13968. (push tg current)))
  13969. (when exit-after-next (setq exit-after-next 'now)))
  13970. ((setq e (rassoc c todo-table) tg (car e))
  13971. (with-current-buffer buf
  13972. (save-excursion (org-todo tg)))
  13973. (when exit-after-next (setq exit-after-next 'now)))
  13974. ((setq e (rassoc c ntable) tg (car e))
  13975. (if (member tg current)
  13976. (setq current (delete tg current))
  13977. (loop for g in groups do
  13978. (when (member tg g)
  13979. (dolist (x g) (setq current (delete x current)))))
  13980. (push tg current))
  13981. (when exit-after-next (setq exit-after-next 'now))))
  13982. ;; Create a sorted list
  13983. (setq current
  13984. (sort current
  13985. (lambda (a b)
  13986. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13987. (when (eq exit-after-next 'now) (throw 'exit t))
  13988. (goto-char (point-min))
  13989. (beginning-of-line 2)
  13990. (delete-region (point) (point-at-eol))
  13991. (org-fast-tag-insert "Current" current c-face)
  13992. (org-set-current-tags-overlay current ov-prefix)
  13993. (while (re-search-forward
  13994. (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
  13995. (setq tg (match-string 1))
  13996. (add-text-properties
  13997. (match-beginning 1) (match-end 1)
  13998. (list 'face
  13999. (cond
  14000. ((member tg current) c-face)
  14001. ((member tg inherited) i-face)
  14002. (t (get-text-property (match-beginning 1) 'face))))))
  14003. (goto-char (point-min)))))
  14004. (org-detach-overlay org-tags-overlay)
  14005. (if rtn
  14006. (mapconcat 'identity current ":")
  14007. nil))))
  14008. (defun org-get-tags-string ()
  14009. "Get the TAGS string in the current headline."
  14010. (unless (org-at-heading-p t)
  14011. (user-error "Not on a heading"))
  14012. (save-excursion
  14013. (beginning-of-line 1)
  14014. (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  14015. (org-match-string-no-properties 1)
  14016. "")))
  14017. (defun org-get-tags ()
  14018. "Get the list of tags specified in the current headline."
  14019. (org-split-string (org-get-tags-string) ":"))
  14020. (defun org-get-buffer-tags ()
  14021. "Get a table of all tags used in the buffer, for completion."
  14022. (org-with-wide-buffer
  14023. (goto-char (point-min))
  14024. (let ((tag-re (concat org-outline-regexp-bol
  14025. "\\(?:.*?[ \t]\\)?"
  14026. (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
  14027. tags)
  14028. (while (re-search-forward tag-re nil t)
  14029. (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
  14030. (push tag tags)))
  14031. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14032. ;;;; The mapping API
  14033. (defun org-map-entries (func &optional match scope &rest skip)
  14034. "Call FUNC at each headline selected by MATCH in SCOPE.
  14035. FUNC is a function or a lisp form. The function will be called without
  14036. arguments, with the cursor positioned at the beginning of the headline.
  14037. The return values of all calls to the function will be collected and
  14038. returned as a list.
  14039. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14040. does not need to preserve point. After evaluation, the cursor will be
  14041. moved to the end of the line (presumably of the headline of the
  14042. processed entry) and search continues from there. Under some
  14043. circumstances, this may not produce the wanted results. For example,
  14044. if you have removed (e.g. archived) the current (sub)tree it could
  14045. mean that the next entry will be skipped entirely. In such cases, you
  14046. can specify the position from where search should continue by making
  14047. FUNC set the variable `org-map-continue-from' to the desired buffer
  14048. position.
  14049. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14050. Only headlines that are matched by this query will be considered during
  14051. the iteration. When MATCH is nil or t, all headlines will be
  14052. visited by the iteration.
  14053. SCOPE determines the scope of this command. It can be any of:
  14054. nil The current buffer, respecting the restriction if any
  14055. tree The subtree started with the entry at point
  14056. region The entries within the active region, if any
  14057. region-start-level
  14058. The entries within the active region, but only those at
  14059. the same level than the first one.
  14060. file The current buffer, without restriction
  14061. file-with-archives
  14062. The current buffer, and any archives associated with it
  14063. agenda All agenda files
  14064. agenda-with-archives
  14065. All agenda files with any archive files associated with them
  14066. \(file1 file2 ...)
  14067. If this is a list, all files in the list will be scanned
  14068. The remaining args are treated as settings for the skipping facilities of
  14069. the scanner. The following items can be given here:
  14070. archive skip trees with the archive tag
  14071. comment skip trees with the COMMENT keyword
  14072. function or Emacs Lisp form:
  14073. will be used as value for `org-agenda-skip-function', so
  14074. whenever the function returns a position, FUNC will not be
  14075. called for that entry and search will continue from the
  14076. position returned
  14077. If your function needs to retrieve the tags including inherited tags
  14078. at the *current* entry, you can use the value of the variable
  14079. `org-scanner-tags' which will be much faster than getting the value
  14080. with `org-get-tags-at'. If your function gets properties with
  14081. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14082. to t around the call to `org-entry-properties' to get the same speedup.
  14083. Note that if your function moves around to retrieve tags and properties at
  14084. a *different* entry, you cannot use these techniques."
  14085. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14086. (not (org-region-active-p)))
  14087. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14088. (org-agenda-skip-archived-trees (memq 'archive skip))
  14089. (org-agenda-skip-comment-trees (memq 'comment skip))
  14090. (org-agenda-skip-function
  14091. (car (org-delete-all '(comment archive) skip)))
  14092. (org-tags-match-list-sublevels t)
  14093. (start-level (eq scope 'region-start-level))
  14094. matcher file res
  14095. org-todo-keywords-for-agenda
  14096. org-done-keywords-for-agenda
  14097. org-todo-keyword-alist-for-agenda
  14098. org-tag-alist-for-agenda
  14099. todo-only)
  14100. (cond
  14101. ((eq match t) (setq matcher t))
  14102. ((eq match nil) (setq matcher t))
  14103. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14104. (save-excursion
  14105. (save-restriction
  14106. (cond ((eq scope 'tree)
  14107. (org-back-to-heading t)
  14108. (org-narrow-to-subtree)
  14109. (setq scope nil))
  14110. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14111. (org-region-active-p))
  14112. ;; If needed, set start-level to a string like "2"
  14113. (when start-level
  14114. (save-excursion
  14115. (goto-char (region-beginning))
  14116. (unless (org-at-heading-p) (outline-next-heading))
  14117. (setq start-level (org-current-level))))
  14118. (narrow-to-region (region-beginning)
  14119. (save-excursion
  14120. (goto-char (region-end))
  14121. (unless (and (bolp) (org-at-heading-p))
  14122. (outline-next-heading))
  14123. (point)))
  14124. (setq scope nil)))
  14125. (if (not scope)
  14126. (progn
  14127. (org-agenda-prepare-buffers
  14128. (and buffer-file-name (list buffer-file-name)))
  14129. (setq res (org-scan-tags func matcher todo-only start-level)))
  14130. ;; Get the right scope
  14131. (cond
  14132. ((and scope (listp scope) (symbolp (car scope)))
  14133. (setq scope (eval scope)))
  14134. ((eq scope 'agenda)
  14135. (setq scope (org-agenda-files t)))
  14136. ((eq scope 'agenda-with-archives)
  14137. (setq scope (org-agenda-files t))
  14138. (setq scope (org-add-archive-files scope)))
  14139. ((eq scope 'file)
  14140. (setq scope (and buffer-file-name (list buffer-file-name))))
  14141. ((eq scope 'file-with-archives)
  14142. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14143. (org-agenda-prepare-buffers scope)
  14144. (dolist (file scope)
  14145. (with-current-buffer (org-find-base-buffer-visiting file)
  14146. (save-excursion
  14147. (save-restriction
  14148. (widen)
  14149. (goto-char (point-min))
  14150. (setq res (append res (org-scan-tags func matcher todo-only))))))))))
  14151. res)))
  14152. ;;; Properties API
  14153. (defconst org-special-properties
  14154. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14155. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14156. "The special properties valid in Org mode.
  14157. These are properties that are not defined in the property drawer,
  14158. but in some other way.")
  14159. (defconst org-default-properties
  14160. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14161. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14162. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14163. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14164. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14165. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14166. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14167. "Some properties that are used by Org mode for various purposes.
  14168. Being in this list makes sure that they are offered for completion.")
  14169. (defun org--update-property-plist (key val props)
  14170. "Associate KEY to VAL in alist PROPS.
  14171. Modifications are made by side-effect. Return new alist."
  14172. (let* ((appending (string= (substring key -1) "+"))
  14173. (key (if appending (substring key 0 -1) key))
  14174. (old (assoc-string key props t)))
  14175. (if (not old) (cons (cons key val) props)
  14176. (setcdr old (if appending (concat (cdr old) " " val) val))
  14177. props)))
  14178. (defun org-get-property-block (&optional beg force)
  14179. "Return the (beg . end) range of the body of the property drawer.
  14180. BEG is the beginning of the current subtree, or of the part
  14181. before the first headline. If it is not given, it will be found.
  14182. If the drawer does not exist, create it if FORCE is non-nil, or
  14183. return nil."
  14184. (org-with-wide-buffer
  14185. (when beg (goto-char beg))
  14186. (unless (org-before-first-heading-p)
  14187. (let ((beg (cond (beg)
  14188. ((or (not (featurep 'org-inlinetask))
  14189. (org-inlinetask-in-task-p))
  14190. (org-back-to-heading t))
  14191. (t (org-with-limited-levels (org-back-to-heading t))))))
  14192. (forward-line)
  14193. (when (org-looking-at-p org-planning-line-re) (forward-line))
  14194. (cond ((looking-at org-property-drawer-re)
  14195. (forward-line)
  14196. (cons (point) (progn (goto-char (match-end 0))
  14197. (line-beginning-position))))
  14198. (force
  14199. (goto-char beg)
  14200. (org-insert-property-drawer)
  14201. (let ((pos (save-excursion (search-forward ":END:")
  14202. (line-beginning-position))))
  14203. (cons pos pos))))))))
  14204. (defun org-at-property-p ()
  14205. "Non-nil when point is inside a property drawer.
  14206. See `org-property-re' for match data, if applicable."
  14207. (save-excursion
  14208. (beginning-of-line)
  14209. (and (looking-at org-property-re)
  14210. (let ((property-drawer (save-match-data (org-get-property-block))))
  14211. (and property-drawer
  14212. (>= (point) (car property-drawer))
  14213. (< (point) (cdr property-drawer)))))))
  14214. (defun org-property-action ()
  14215. "Do an action on properties."
  14216. (interactive)
  14217. (unless (org-at-property-p) (user-error "Not at a property"))
  14218. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14219. (let ((c (read-char-exclusive)))
  14220. (case c
  14221. (?s (call-interactively #'org-set-property))
  14222. (?d (call-interactively #'org-delete-property))
  14223. (?D (call-interactively #'org-delete-property-globally))
  14224. (?c (call-interactively #'org-compute-property-at-point))
  14225. (otherwise (user-error "No such property action %c" c)))))
  14226. (defun org-inc-effort ()
  14227. "Increment the value of the effort property in the current entry."
  14228. (interactive)
  14229. (org-set-effort nil t))
  14230. (defvar org-clock-effort) ; Defined in org-clock.el.
  14231. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14232. (defun org-set-effort (&optional value increment)
  14233. "Set the effort property of the current entry.
  14234. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14235. 10th allowed value.
  14236. When INCREMENT is non-nil, set the property to the next allowed value."
  14237. (interactive "P")
  14238. (when (equal value 0) (setq value 10))
  14239. (let* ((completion-ignore-case t)
  14240. (prop org-effort-property)
  14241. (cur (org-entry-get nil prop))
  14242. (allowed (org-property-get-allowed-values nil prop 'table))
  14243. (existing (mapcar 'list (org-property-values prop)))
  14244. (heading (nth 4 (org-heading-components)))
  14245. rpl
  14246. (val (cond
  14247. ((stringp value) value)
  14248. ((and allowed (integerp value))
  14249. (or (car (nth (1- value) allowed))
  14250. (car (org-last allowed))))
  14251. ((and allowed increment)
  14252. (or (caadr (member (list cur) allowed))
  14253. (user-error "Allowed effort values are not set")))
  14254. (allowed
  14255. (message "Select 1-9,0, [RET%s]: %s"
  14256. (if cur (concat "=" cur) "")
  14257. (mapconcat 'car allowed " "))
  14258. (setq rpl (read-char-exclusive))
  14259. (if (equal rpl ?\r)
  14260. cur
  14261. (setq rpl (- rpl ?0))
  14262. (when (equal rpl 0) (setq rpl 10))
  14263. (if (and (> rpl 0) (<= rpl (length allowed)))
  14264. (car (nth (1- rpl) allowed))
  14265. (org-completing-read "Effort: " allowed nil))))
  14266. (t
  14267. (let (org-completion-use-ido org-completion-use-iswitchb)
  14268. (org-completing-read
  14269. (concat "Effort " (if (and cur (string-match "\\S-" cur))
  14270. (concat "[" cur "]") "")
  14271. ": ")
  14272. existing nil nil "" nil cur))))))
  14273. (unless (equal (org-entry-get nil prop) val)
  14274. (org-entry-put nil prop val))
  14275. (org-refresh-property
  14276. '((effort . identity)
  14277. (effort-minutes . org-duration-string-to-minutes))
  14278. val)
  14279. (when (string= heading org-clock-current-task)
  14280. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14281. (org-clock-update-mode-line))
  14282. (message "%s is now %s" prop val)))
  14283. (defun org-entry-properties (&optional pom which)
  14284. "Get all properties of the current entry.
  14285. When POM is a buffer position, get all properties from the entry
  14286. there instead.
  14287. This includes the TODO keyword, the tags, time strings for
  14288. deadline, scheduled, and clocking, and any additional properties
  14289. defined in the entry.
  14290. If WHICH is nil or `all', get all properties. If WHICH is
  14291. `special' or `standard', only get that subclass. If WHICH is
  14292. a string, only get that property.
  14293. Return value is an alist. Keys are properties, as upcased
  14294. strings."
  14295. (org-with-point-at pom
  14296. (when (and (derived-mode-p 'org-mode)
  14297. (ignore-errors (org-back-to-heading t)))
  14298. (catch 'exit
  14299. (let* ((beg (point))
  14300. (specific (and (stringp which) (upcase which)))
  14301. (which (cond ((not specific) which)
  14302. ((member specific org-special-properties) 'special)
  14303. (t 'standard)))
  14304. props)
  14305. ;; Get the special properties, like TODO and TAGS.
  14306. (when (memq which '(nil all special))
  14307. (when (or (not specific) (string= specific "CLOCKSUM"))
  14308. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14309. (when clocksum
  14310. (push (cons "CLOCKSUM"
  14311. (org-columns-number-to-string
  14312. (/ (float clocksum) 60.) 'add_times))
  14313. props)))
  14314. (when specific (throw 'exit props)))
  14315. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14316. (let ((clocksumt (get-text-property (point)
  14317. :org-clock-minutes-today)))
  14318. (when clocksumt
  14319. (push (cons "CLOCKSUM_T"
  14320. (org-columns-number-to-string
  14321. (/ (float clocksumt) 60.) 'add_times))
  14322. props)))
  14323. (when specific (throw 'exit props)))
  14324. (when (or (not specific) (string= specific "ITEM"))
  14325. (when (looking-at org-complex-heading-regexp)
  14326. (push (cons "ITEM"
  14327. (concat
  14328. (org-match-string-no-properties 1)
  14329. (let ((title (org-match-string-no-properties 4)))
  14330. (when (org-string-nw-p title)
  14331. (concat " " (org-remove-tabs title))))))
  14332. props))
  14333. (when specific (throw 'exit props)))
  14334. (when (or (not specific) (string= specific "TODO"))
  14335. (let ((case-fold-search nil))
  14336. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14337. (push (cons "TODO" (org-match-string-no-properties 2)) props)))
  14338. (when specific (throw 'exit props)))
  14339. (when (or (not specific) (string= specific "PRIORITY"))
  14340. (push (cons "PRIORITY"
  14341. (if (looking-at org-priority-regexp)
  14342. (org-match-string-no-properties 2)
  14343. (char-to-string org-default-priority)))
  14344. props)
  14345. (when specific (throw 'exit props)))
  14346. (when (or (not specific) (string= specific "FILE"))
  14347. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14348. props)
  14349. (when specific (throw 'exit props)))
  14350. (when (or (not specific) (string= specific "TAGS"))
  14351. (let ((value (org-string-nw-p (org-get-tags-string))))
  14352. (when value (push (cons "TAGS" value) props)))
  14353. (when specific (throw 'exit props)))
  14354. (when (or (not specific) (string= specific "ALLTAGS"))
  14355. (let ((value (org-get-tags-at)))
  14356. (when value
  14357. (push (cons "ALLTAGS"
  14358. (format ":%s:" (mapconcat #'identity value ":")))
  14359. props)))
  14360. (when specific (throw 'exit props)))
  14361. (when (or (not specific) (string= specific "BLOCKED"))
  14362. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14363. (when specific (throw 'exit props)))
  14364. (when (or (not specific)
  14365. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14366. (forward-line)
  14367. (when (org-looking-at-p org-planning-line-re)
  14368. (end-of-line)
  14369. (let ((bol (line-beginning-position))
  14370. ;; Backward compatibility: time keywords used to
  14371. ;; be configurable (before 8.3). Make sure we
  14372. ;; get the correct keyword.
  14373. (key-assoc `(("CLOSED" . ,org-closed-string)
  14374. ("DEADLINE" . ,org-deadline-string)
  14375. ("SCHEDULED" . ,org-scheduled-string))))
  14376. (dolist (pair (if specific (list (assoc specific key-assoc))
  14377. key-assoc))
  14378. (save-excursion
  14379. (when (search-backward (cdr pair) bol t)
  14380. (goto-char (match-end 0))
  14381. (skip-chars-forward " \t")
  14382. (and (looking-at org-ts-regexp-both)
  14383. (push (cons (car pair)
  14384. (org-match-string-no-properties 0))
  14385. props)))))))
  14386. (when specific (throw 'exit props)))
  14387. (when (or (not specific)
  14388. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14389. (let ((find-ts
  14390. (lambda (end ts)
  14391. (let ((regexp (cond
  14392. ((string= specific "TIMESTAMP")
  14393. org-ts-regexp)
  14394. ((string= specific "TIMESTAMP_IA")
  14395. org-ts-regexp-inactive)
  14396. ((assoc "TIMESTAMP_IA" ts)
  14397. org-ts-regexp)
  14398. ((assoc "TIMESTAMP" ts)
  14399. org-ts-regexp-inactive)
  14400. (t org-ts-regexp-both))))
  14401. (catch 'next
  14402. (while (re-search-forward regexp end t)
  14403. (backward-char)
  14404. (let ((object (org-element-context)))
  14405. ;; Accept to match timestamps in node
  14406. ;; properties, too.
  14407. (when (memq (org-element-type object)
  14408. '(node-property timestamp))
  14409. (let ((type
  14410. (org-element-property :type object)))
  14411. (cond
  14412. ((and (memq type '(active active-range))
  14413. (not (equal specific "TIMESTAMP_IA")))
  14414. (unless (assoc "TIMESTAMP" ts)
  14415. (push (cons "TIMESTAMP"
  14416. (org-element-property
  14417. :raw-value object))
  14418. ts)
  14419. (when specific (throw 'exit ts))))
  14420. ((and (memq type '(inactive inactive-range))
  14421. (not (string= specific "TIMESTAMP")))
  14422. (unless (assoc "TIMESTAMP_IA" ts)
  14423. (push (cons "TIMESTAMP_IA"
  14424. (org-element-property
  14425. :raw-value object))
  14426. ts)
  14427. (when specific (throw 'exit ts))))))
  14428. ;; Both timestamp types are found,
  14429. ;; move to next part.
  14430. (when (= (length ts) 2) (throw 'next ts)))))
  14431. ts)))))
  14432. (goto-char beg)
  14433. ;; First look for timestamps within headline.
  14434. (let ((ts (funcall find-ts (line-end-position) nil)))
  14435. (if (= (length ts) 2) (setq props (nconc ts props))
  14436. (forward-line)
  14437. ;; Then find timestamps in the section, skipping
  14438. ;; planning line.
  14439. (when (org-looking-at-p org-planning-line-re)
  14440. (forward-line))
  14441. (let ((end (save-excursion (outline-next-heading))))
  14442. (setq props (nconc (funcall find-ts end ts) props))))))))
  14443. ;; Get the standard properties, like :PROP:.
  14444. (when (memq which '(nil all standard))
  14445. ;; If we are looking after a specific property, delegate
  14446. ;; to `org-entry-get', which is faster. However, make an
  14447. ;; exception for "CATEGORY", since it can be also set
  14448. ;; through keywords (i.e. #+CATEGORY).
  14449. (if (and specific (not (equal specific "CATEGORY")))
  14450. (let ((value (org-entry-get beg specific nil t)))
  14451. (throw 'exit (and value (list (cons specific value)))))
  14452. (let ((range (org-get-property-block beg)))
  14453. (when range
  14454. (let ((end (cdr range)) seen-base)
  14455. (goto-char (car range))
  14456. ;; Unlike to `org--update-property-plist', we
  14457. ;; handle the case where base values is found
  14458. ;; after its extension. We also forbid standard
  14459. ;; properties to be named as special properties.
  14460. (while (re-search-forward org-property-re end t)
  14461. (let* ((key (upcase (org-match-string-no-properties 2)))
  14462. (extendp (org-string-match-p "\\+\\'" key))
  14463. (key-base (if extendp (substring key 0 -1) key))
  14464. (value (org-match-string-no-properties 3)))
  14465. (cond
  14466. ((member-ignore-case key-base org-special-properties))
  14467. (extendp
  14468. (setq props
  14469. (org--update-property-plist key value props)))
  14470. ((member key seen-base))
  14471. (t (push key seen-base)
  14472. (let ((p (assoc-string key props t)))
  14473. (if p (setcdr p (concat value " " (cdr p)))
  14474. (push (cons key value) props))))))))))))
  14475. (unless (assoc "CATEGORY" props)
  14476. (push (cons "CATEGORY" (org-get-category beg)) props)
  14477. (when (string= specific "CATEGORY") (throw 'exit props)))
  14478. ;; Return value.
  14479. props)))))
  14480. (defun org-property--local-values (property literal-nil)
  14481. "Return value for PROPERTY in current entry.
  14482. Value is a list whose care is the base value for PROPERTY and cdr
  14483. a list of accumulated values. Return nil if neither is found in
  14484. the entry. Also return nil when PROPERTY is set to \"nil\",
  14485. unless LITERAL-NIL is non-nil."
  14486. (let ((range (org-get-property-block)))
  14487. (when range
  14488. (goto-char (car range))
  14489. (let* ((case-fold-search t)
  14490. (end (cdr range))
  14491. (value
  14492. ;; Base value.
  14493. (save-excursion
  14494. (let ((v (and (re-search-forward
  14495. (org-re-property property nil t) end t)
  14496. (org-match-string-no-properties 3))))
  14497. (list (if literal-nil v (org-not-nil v)))))))
  14498. ;; Find additional values.
  14499. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14500. (while (re-search-forward property+ end t)
  14501. (push (org-match-string-no-properties 3) value)))
  14502. ;; Return final values.
  14503. (and (not (equal value '(nil))) (nreverse value))))))
  14504. (defun org-entry-get (pom property &optional inherit literal-nil)
  14505. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14506. If INHERIT is non-nil and the entry does not have the property,
  14507. then also check higher levels of the hierarchy. If INHERIT is
  14508. the symbol `selective', use inheritance only if the setting in
  14509. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14510. If the property is present but empty, the return value is the
  14511. empty string. If the property is not present at all, nil is
  14512. returned. In any other case, return the value as a string.
  14513. Search is case-insensitive.
  14514. If LITERAL-NIL is set, return the string value \"nil\" as
  14515. a string, do not interpret it as the list atom nil. This is used
  14516. for inheritance when a \"nil\" value can supersede a non-nil
  14517. value higher up the hierarchy."
  14518. (org-with-point-at pom
  14519. (cond
  14520. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14521. ;; We need a special property. Use `org-entry-properties' to
  14522. ;; retrieve it, but specify the wanted property.
  14523. (cdr (assoc-string property (org-entry-properties nil property))))
  14524. ((and inherit
  14525. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14526. (org-entry-get-with-inheritance property literal-nil))
  14527. (t
  14528. (let* ((local (org-property--local-values property literal-nil))
  14529. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14530. (if literal-nil value (org-not-nil value)))))))
  14531. (defun org-property-or-variable-value (var &optional inherit)
  14532. "Check if there is a property fixing the value of VAR.
  14533. If yes, return this value. If not, return the current value of the variable."
  14534. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14535. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14536. (read prop)
  14537. (symbol-value var))))
  14538. (defun org-entry-delete (pom property)
  14539. "Delete PROPERTY from entry at point-or-marker POM.
  14540. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14541. non-nil when a property was removed."
  14542. (unless (member property org-special-properties)
  14543. (org-with-point-at pom
  14544. (let ((range (org-get-property-block)))
  14545. (when range
  14546. (let* ((begin (car range))
  14547. (origin (cdr range))
  14548. (end (copy-marker origin))
  14549. (re (org-re-property
  14550. (concat (regexp-quote property) "\\+?") t t)))
  14551. (goto-char begin)
  14552. (while (re-search-forward re end t)
  14553. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14554. ;; If drawer is empty, remove it altogether.
  14555. (when (= begin end)
  14556. (delete-region (line-beginning-position 0)
  14557. (line-beginning-position 2)))
  14558. ;; Return non-nil if some property was removed.
  14559. (prog1 (/= end origin) (set-marker end nil))))))))
  14560. ;; Multi-values properties are properties that contain multiple values
  14561. ;; These values are assumed to be single words, separated by whitespace.
  14562. (defun org-entry-add-to-multivalued-property (pom property value)
  14563. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14564. (let* ((old (org-entry-get pom property))
  14565. (values (and old (org-split-string old "[ \t]"))))
  14566. (setq value (org-entry-protect-space value))
  14567. (unless (member value values)
  14568. (setq values (append values (list value)))
  14569. (org-entry-put pom property
  14570. (mapconcat 'identity values " ")))))
  14571. (defun org-entry-remove-from-multivalued-property (pom property value)
  14572. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14573. (let* ((old (org-entry-get pom property))
  14574. (values (and old (org-split-string old "[ \t]"))))
  14575. (setq value (org-entry-protect-space value))
  14576. (when (member value values)
  14577. (setq values (delete value values))
  14578. (org-entry-put pom property
  14579. (mapconcat 'identity values " ")))))
  14580. (defun org-entry-member-in-multivalued-property (pom property value)
  14581. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14582. (let* ((old (org-entry-get pom property))
  14583. (values (and old (org-split-string old "[ \t]"))))
  14584. (setq value (org-entry-protect-space value))
  14585. (member value values)))
  14586. (defun org-entry-get-multivalued-property (pom property)
  14587. "Return a list of values in a multivalued property."
  14588. (let* ((value (org-entry-get pom property))
  14589. (values (and value (org-split-string value "[ \t]"))))
  14590. (mapcar 'org-entry-restore-space values)))
  14591. (defun org-entry-put-multivalued-property (pom property &rest values)
  14592. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14593. VALUES should be a list of strings. Spaces will be protected."
  14594. (org-entry-put pom property
  14595. (mapconcat 'org-entry-protect-space values " "))
  14596. (let* ((value (org-entry-get pom property))
  14597. (values (and value (org-split-string value "[ \t]"))))
  14598. (mapcar 'org-entry-restore-space values)))
  14599. (defun org-entry-protect-space (s)
  14600. "Protect spaces and newline in string S."
  14601. (while (string-match " " s)
  14602. (setq s (replace-match "%20" t t s)))
  14603. (while (string-match "\n" s)
  14604. (setq s (replace-match "%0A" t t s)))
  14605. s)
  14606. (defun org-entry-restore-space (s)
  14607. "Restore spaces and newline in string S."
  14608. (while (string-match "%20" s)
  14609. (setq s (replace-match " " t t s)))
  14610. (while (string-match "%0A" s)
  14611. (setq s (replace-match "\n" t t s)))
  14612. s)
  14613. (defvar org-entry-property-inherited-from (make-marker)
  14614. "Marker pointing to the entry from where a property was inherited.
  14615. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14616. location of the entry where the inheritance search matched. If there was
  14617. no match, the marker will point nowhere.
  14618. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14619. is set.")
  14620. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14621. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14622. The search will stop at the first ancestor which has the property defined.
  14623. If the value found is \"nil\", return nil to show that the property
  14624. should be considered as undefined (this is the meaning of nil here).
  14625. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14626. (move-marker org-entry-property-inherited-from nil)
  14627. (org-with-wide-buffer
  14628. (let (value)
  14629. (catch 'exit
  14630. (while t
  14631. (let ((v (org-property--local-values property literal-nil)))
  14632. (when v
  14633. (setq value
  14634. (concat (mapconcat #'identity (delq nil v) " ")
  14635. (and value " ")
  14636. value)))
  14637. (cond
  14638. ((car v)
  14639. (org-back-to-heading t)
  14640. (move-marker org-entry-property-inherited-from (point))
  14641. (throw 'exit nil))
  14642. ((org-up-heading-safe))
  14643. (t
  14644. (let ((global
  14645. (cdr (or (assoc-string property org-file-properties t)
  14646. (assoc-string property org-global-properties t)
  14647. (assoc-string property org-global-properties-fixed t)))))
  14648. (cond ((not global))
  14649. (value (setq value (concat global " " value)))
  14650. (t (setq value global))))
  14651. (throw 'exit nil))))))
  14652. (if literal-nil value (org-not-nil value)))))
  14653. (defvar org-property-changed-functions nil
  14654. "Hook called when the value of a property has changed.
  14655. Each hook function should accept two arguments, the name of the property
  14656. and the new value.")
  14657. (defun org-entry-put (pom property value)
  14658. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14659. If the value is nil, it is converted to the empty string. If
  14660. it is not a string, an error is raised.
  14661. PROPERTY can be any regular property (see
  14662. `org-special-properties'). It can also be \"TODO\",
  14663. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14664. For the last two properties, VALUE may have any of the special
  14665. values \"earlier\" and \"later\". The function then increases or
  14666. decreases scheduled or deadline date by one day."
  14667. (cond ((null value) (setq value ""))
  14668. ((not (stringp value)) (error "Properties values should be strings")))
  14669. (org-with-point-at pom
  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. (let ((beg (point)))
  14674. (cond
  14675. ((equal property "TODO")
  14676. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14677. ((not (member value org-todo-keywords-1))
  14678. (user-error "\"%s\" is not a valid TODO state" value)))
  14679. (org-todo value)
  14680. (org-set-tags nil 'align))
  14681. ((equal property "PRIORITY")
  14682. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14683. (org-set-tags nil 'align))
  14684. ((equal property "SCHEDULED")
  14685. (forward-line)
  14686. (if (and (org-looking-at-p org-planning-line-re)
  14687. (re-search-forward
  14688. org-scheduled-time-regexp (line-end-position) t))
  14689. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14690. ((string= value "later") (org-timestamp-change 1 'day))
  14691. ((string= value "") (org-schedule '(4)))
  14692. (t (org-schedule nil value)))
  14693. (if (member value '("earlier" "later" ""))
  14694. (call-interactively #'org-schedule)
  14695. (org-schedule nil value))))
  14696. ((equal property "DEADLINE")
  14697. (forward-line)
  14698. (if (and (org-looking-at-p org-planning-line-re)
  14699. (re-search-forward
  14700. org-deadline-time-regexp (line-end-position) t))
  14701. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14702. ((string= value "later") (org-timestamp-change 1 'day))
  14703. ((string= value "") (org-deadline '(4)))
  14704. (t (org-deadline nil value)))
  14705. (if (member value '("earlier" "later" ""))
  14706. (call-interactively #'org-deadline)
  14707. (org-deadline nil value))))
  14708. ((member property org-special-properties)
  14709. (error "The %s property cannot be set with `org-entry-put'" property))
  14710. (t
  14711. (let* ((range (org-get-property-block beg 'force))
  14712. (end (cdr range))
  14713. (case-fold-search t))
  14714. (goto-char (car range))
  14715. (if (re-search-forward (org-re-property property nil t) end t)
  14716. (progn (delete-region (match-beginning 0) (match-end 0))
  14717. (goto-char (match-beginning 0)))
  14718. (goto-char end)
  14719. (insert "\n")
  14720. (backward-char))
  14721. (insert ":" property ":")
  14722. (when value (insert " " value))
  14723. (org-indent-line)))))
  14724. (run-hook-with-args 'org-property-changed-functions property value)))
  14725. (defun org-buffer-property-keys (&optional specials defaults columns)
  14726. "Get all property keys in the current buffer.
  14727. When SPECIALS is non-nil, also list the special properties that
  14728. reflect things like tags and TODO state.
  14729. When DEFAULTS is non-nil, also include properties that has
  14730. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14731. DESCRIPTION, LOCATION, and LOGGING and others.
  14732. When COLUMNS in non-nil, also include property names given in
  14733. COLUMN formats in the current buffer."
  14734. (let ((case-fold-search t)
  14735. (props (append
  14736. (and specials org-special-properties)
  14737. (and defaults (cons org-effort-property org-default-properties))
  14738. nil)))
  14739. (org-with-wide-buffer
  14740. (goto-char (point-min))
  14741. (while (re-search-forward org-property-start-re nil t)
  14742. (let ((range (org-get-property-block)))
  14743. (catch 'skip
  14744. (unless range
  14745. (when (and (not (org-before-first-heading-p))
  14746. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14747. (line-beginning-position))))
  14748. (org-get-property-block nil t))
  14749. (throw 'skip nil))
  14750. (goto-char (car range))
  14751. (let ((begin (car range))
  14752. (end (cdr range)))
  14753. ;; Make sure that found property block is not located
  14754. ;; before current point, as it would generate an infloop.
  14755. ;; It can happen, for example, in the following
  14756. ;; situation:
  14757. ;;
  14758. ;; * Headline
  14759. ;; :PROPERTIES:
  14760. ;; ...
  14761. ;; :END:
  14762. ;; *************** Inlinetask
  14763. ;; #+BEGIN_EXAMPLE
  14764. ;; :PROPERTIES:
  14765. ;; #+END_EXAMPLE
  14766. ;;
  14767. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14768. (while (< (point) end)
  14769. (let ((p (progn (looking-at org-property-re)
  14770. (org-match-string-no-properties 2))))
  14771. ;; Only add true property name, not extension symbol.
  14772. (add-to-list 'props
  14773. (if (not (org-string-match-p "\\+\\'" p)) p
  14774. (substring p 0 -1))))
  14775. (forward-line))))
  14776. (outline-next-heading)))
  14777. (when columns
  14778. (goto-char (point-min))
  14779. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14780. (let ((element (org-element-at-point)))
  14781. (when (memq (org-element-type element) '(keyword node-property))
  14782. (let ((value (org-element-property :value element))
  14783. (start 0))
  14784. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14785. (setq start (match-end 0))
  14786. (let ((p (org-match-string-no-properties 1 value)))
  14787. (unless (member-ignore-case p org-special-properties)
  14788. (add-to-list 'props p))))))))))
  14789. (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
  14790. (defun org-property-values (key)
  14791. "List all non-nil values of property KEY in current buffer."
  14792. (org-with-wide-buffer
  14793. (goto-char (point-min))
  14794. (let ((case-fold-search t)
  14795. (re (org-re-property key))
  14796. values)
  14797. (while (re-search-forward re nil t)
  14798. (add-to-list 'values (org-entry-get (point) key)))
  14799. values)))
  14800. (defun org-insert-property-drawer ()
  14801. "Insert a property drawer into the current entry."
  14802. (org-with-wide-buffer
  14803. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14804. (org-back-to-heading t)
  14805. (org-with-limited-levels (org-back-to-heading t)))
  14806. (forward-line)
  14807. (when (org-looking-at-p org-planning-line-re) (forward-line))
  14808. (unless (org-looking-at-p org-property-drawer-re)
  14809. ;; Make sure we start editing a line from current entry, not from
  14810. ;; next one. It prevents extending text properties or overlays
  14811. ;; belonging to the latter.
  14812. (when (bolp) (backward-char))
  14813. (let ((begin (1+ (point)))
  14814. (inhibit-read-only t))
  14815. (insert "\n:PROPERTIES:\n:END:")
  14816. (when (eobp) (insert "\n"))
  14817. (org-indent-region begin (point))))))
  14818. (defun org-insert-drawer (&optional arg drawer)
  14819. "Insert a drawer at point.
  14820. When optional argument ARG is non-nil, insert a property drawer.
  14821. Optional argument DRAWER, when non-nil, is a string representing
  14822. drawer's name. Otherwise, the user is prompted for a name.
  14823. If a region is active, insert the drawer around that region
  14824. instead.
  14825. Point is left between drawer's boundaries."
  14826. (interactive "P")
  14827. (let* ((drawer (if arg "PROPERTIES"
  14828. (or drawer (read-from-minibuffer "Drawer: ")))))
  14829. (cond
  14830. ;; With C-u, fall back on `org-insert-property-drawer'
  14831. (arg (org-insert-property-drawer))
  14832. ;; Check validity of suggested drawer's name.
  14833. ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14834. (user-error "Invalid drawer name"))
  14835. ;; With an active region, insert a drawer at point.
  14836. ((not (org-region-active-p))
  14837. (progn
  14838. (unless (bolp) (insert "\n"))
  14839. (insert (format ":%s:\n\n:END:\n" drawer))
  14840. (forward-line -2)))
  14841. ;; Otherwise, insert the drawer at point
  14842. (t
  14843. (let ((rbeg (region-beginning))
  14844. (rend (copy-marker (region-end))))
  14845. (unwind-protect
  14846. (progn
  14847. (goto-char rbeg)
  14848. (beginning-of-line)
  14849. (when (save-excursion
  14850. (re-search-forward org-outline-regexp-bol rend t))
  14851. (user-error "Drawers cannot contain headlines"))
  14852. ;; Position point at the beginning of the first
  14853. ;; non-blank line in region. Insert drawer's opening
  14854. ;; there, then indent it.
  14855. (org-skip-whitespace)
  14856. (beginning-of-line)
  14857. (insert ":" drawer ":\n")
  14858. (forward-line -1)
  14859. (indent-for-tab-command)
  14860. ;; Move point to the beginning of the first blank line
  14861. ;; after the last non-blank line in region. Insert
  14862. ;; drawer's closing, then indent it.
  14863. (goto-char rend)
  14864. (skip-chars-backward " \r\t\n")
  14865. (insert "\n:END:")
  14866. (deactivate-mark t)
  14867. (indent-for-tab-command)
  14868. (unless (eolp) (insert "\n")))
  14869. ;; Clear marker, whatever the outcome of insertion is.
  14870. (set-marker rend nil)))))))
  14871. (defvar org-property-set-functions-alist nil
  14872. "Property set function alist.
  14873. Each entry should have the following format:
  14874. (PROPERTY . READ-FUNCTION)
  14875. The read function will be called with the same argument as
  14876. `org-completing-read'.")
  14877. (defun org-set-property-function (property)
  14878. "Get the function that should be used to set PROPERTY.
  14879. This is computed according to `org-property-set-functions-alist'."
  14880. (or (cdr (assoc property org-property-set-functions-alist))
  14881. 'org-completing-read))
  14882. (defun org-read-property-value (property)
  14883. "Read PROPERTY value from user."
  14884. (let* ((completion-ignore-case t)
  14885. (allowed (org-property-get-allowed-values nil property 'table))
  14886. (cur (org-entry-get nil property))
  14887. (prompt (concat property " value"
  14888. (if (and cur (string-match "\\S-" cur))
  14889. (concat " [" cur "]") "") ": "))
  14890. (set-function (org-set-property-function property))
  14891. (val (if allowed
  14892. (funcall set-function prompt allowed nil
  14893. (not (get-text-property 0 'org-unrestricted
  14894. (caar allowed))))
  14895. (let (org-completion-use-ido org-completion-use-iswitchb)
  14896. (funcall set-function prompt
  14897. (mapcar 'list (org-property-values property))
  14898. nil nil "" nil cur)))))
  14899. (org-trim val)))
  14900. (defvar org-last-set-property nil)
  14901. (defvar org-last-set-property-value nil)
  14902. (defun org-read-property-name ()
  14903. "Read a property name."
  14904. (let ((completion-ignore-case t)
  14905. (default-prop (or (and (org-at-property-p)
  14906. (org-match-string-no-properties 2))
  14907. org-last-set-property)))
  14908. (org-completing-read
  14909. (concat "Property"
  14910. (if default-prop (concat " [" default-prop "]") "")
  14911. ": ")
  14912. (mapcar #'list (org-buffer-property-keys nil t t))
  14913. nil nil nil nil default-prop)))
  14914. (defun org-set-property-and-value (use-last)
  14915. "Allow to set [PROPERTY]: [value] direction from prompt.
  14916. When use-default, don't even ask, just use the last
  14917. \"[PROPERTY]: [value]\" string from the history."
  14918. (interactive "P")
  14919. (let* ((completion-ignore-case t)
  14920. (pv (or (and use-last org-last-set-property-value)
  14921. (org-completing-read
  14922. "Enter a \"[Property]: [value]\" pair: "
  14923. nil nil nil nil nil
  14924. org-last-set-property-value)))
  14925. prop val)
  14926. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14927. (setq prop (match-string 1 pv)
  14928. val (match-string 2 pv))
  14929. (org-set-property prop val))))
  14930. (defun org-set-property (property value)
  14931. "In the current entry, set PROPERTY to VALUE.
  14932. When called interactively, this will prompt for a property name, offering
  14933. completion on existing and default properties. And then it will prompt
  14934. for a value, offering completion either on allowed values (via an inherited
  14935. xxx_ALL property) or on existing values in other instances of this property
  14936. in the current file."
  14937. (interactive (list nil nil))
  14938. (let* ((property (or property (org-read-property-name)))
  14939. (value (or value (org-read-property-value property)))
  14940. (fn (cdr (assoc property org-properties-postprocess-alist))))
  14941. (setq org-last-set-property property)
  14942. (setq org-last-set-property-value (concat property ": " value))
  14943. ;; Possibly postprocess the inserted value:
  14944. (when fn (setq value (funcall fn value)))
  14945. (unless (equal (org-entry-get nil property) value)
  14946. (org-entry-put nil property value))))
  14947. (defun org-find-property (property &optional value)
  14948. "Find first entry in buffer that sets PROPERTY.
  14949. When optional argument VALUE is non-nil, only consider an entry
  14950. if it contains PROPERTY set to this value. If PROPERTY should be
  14951. explicitly set to nil, use string \"nil\" for VALUE.
  14952. Return position where the entry begins, or nil if there is no
  14953. such entry. If narrowing is in effect, only search the visible
  14954. part of the buffer."
  14955. (save-excursion
  14956. (goto-char (point-min))
  14957. (let ((case-fold-search t)
  14958. (re (org-re-property property nil (not value) value)))
  14959. (catch 'exit
  14960. (while (re-search-forward re nil t)
  14961. (when (if value (org-at-property-p)
  14962. (org-entry-get (point) property nil t))
  14963. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14964. (defun org-delete-property (property)
  14965. "In the current entry, delete PROPERTY."
  14966. (interactive
  14967. (let* ((completion-ignore-case t)
  14968. (cat (org-entry-get (point) "CATEGORY"))
  14969. (props0 (org-entry-properties nil 'standard))
  14970. (props (if cat props0
  14971. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14972. (prop (if (< 1 (length props))
  14973. (org-icompleting-read "Property: " props nil t)
  14974. (caar props))))
  14975. (list prop)))
  14976. (if (not property)
  14977. (message "No property to delete in this entry")
  14978. (org-entry-delete nil property)
  14979. (message "Property \"%s\" deleted" property)))
  14980. (defun org-delete-property-globally (property)
  14981. "Remove PROPERTY globally, from all entries.
  14982. This function ignores narrowing, if any."
  14983. (interactive
  14984. (let* ((completion-ignore-case t)
  14985. (prop (org-icompleting-read
  14986. "Globally remove property: "
  14987. (mapcar #'list (org-buffer-property-keys)))))
  14988. (list prop)))
  14989. (org-with-wide-buffer
  14990. (goto-char (point-min))
  14991. (let ((count 0)
  14992. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14993. (while (re-search-forward re nil t)
  14994. (when (org-entry-delete (point) property) (incf count)))
  14995. (message "Property \"%s\" removed from %d entries" property count))))
  14996. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14997. (defun org-compute-property-at-point ()
  14998. "Compute the property at point.
  14999. This looks for an enclosing column format, extracts the operator and
  15000. then applies it to the property in the column format's scope."
  15001. (interactive)
  15002. (unless (org-at-property-p)
  15003. (user-error "Not at a property"))
  15004. (let ((prop (org-match-string-no-properties 2)))
  15005. (org-columns-get-format-and-top-level)
  15006. (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
  15007. (user-error "No operator defined for property %s" prop))
  15008. (org-columns-compute prop)))
  15009. (defvar org-property-allowed-value-functions nil
  15010. "Hook for functions supplying allowed values for a specific property.
  15011. The functions must take a single argument, the name of the property, and
  15012. return a flat list of allowed values. If \":ETC\" is one of
  15013. the values, this means that these values are intended as defaults for
  15014. completion, but that other values should be allowed too.
  15015. The functions must return nil if they are not responsible for this
  15016. property.")
  15017. (defun org-property-get-allowed-values (pom property &optional table)
  15018. "Get allowed values for the property PROPERTY.
  15019. When TABLE is non-nil, return an alist that can directly be used for
  15020. completion."
  15021. (let (vals)
  15022. (cond
  15023. ((equal property "TODO")
  15024. (setq vals (org-with-point-at pom
  15025. (append org-todo-keywords-1 '("")))))
  15026. ((equal property "PRIORITY")
  15027. (let ((n org-lowest-priority))
  15028. (while (>= n org-highest-priority)
  15029. (push (char-to-string n) vals)
  15030. (setq n (1- n)))))
  15031. ((equal property "CATEGORY"))
  15032. ((member property org-special-properties))
  15033. ((setq vals (run-hook-with-args-until-success
  15034. 'org-property-allowed-value-functions property)))
  15035. (t
  15036. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15037. (when (and vals (string-match "\\S-" vals))
  15038. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15039. (setq vals (mapcar (lambda (x)
  15040. (cond ((stringp x) x)
  15041. ((numberp x) (number-to-string x))
  15042. ((symbolp x) (symbol-name x))
  15043. (t "???")))
  15044. vals)))))
  15045. (when (member ":ETC" vals)
  15046. (setq vals (remove ":ETC" vals))
  15047. (org-add-props (car vals) '(org-unrestricted t)))
  15048. (if table (mapcar 'list vals) vals)))
  15049. (defun org-property-previous-allowed-value (&optional previous)
  15050. "Switch to the next allowed value for this property."
  15051. (interactive)
  15052. (org-property-next-allowed-value t))
  15053. (defun org-property-next-allowed-value (&optional previous)
  15054. "Switch to the next allowed value for this property."
  15055. (interactive)
  15056. (unless (org-at-property-p)
  15057. (user-error "Not at a property"))
  15058. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15059. (key (match-string 2))
  15060. (value (match-string 3))
  15061. (allowed (or (org-property-get-allowed-values (point) key)
  15062. (and (member value '("[ ]" "[-]" "[X]"))
  15063. '("[ ]" "[X]"))))
  15064. (heading (save-match-data (nth 4 (org-heading-components))))
  15065. nval)
  15066. (unless allowed
  15067. (user-error "Allowed values for this property have not been defined"))
  15068. (when previous (setq allowed (reverse allowed)))
  15069. (when (member value allowed)
  15070. (setq nval (car (cdr (member value allowed)))))
  15071. (setq nval (or nval (car allowed)))
  15072. (when (equal nval value)
  15073. (user-error "Only one allowed value for this property"))
  15074. (org-at-property-p)
  15075. (replace-match (concat " :" key ": " nval) t t)
  15076. (org-indent-line)
  15077. (beginning-of-line 1)
  15078. (skip-chars-forward " \t")
  15079. (when (equal prop org-effort-property)
  15080. (org-refresh-property
  15081. '((effort . identity)
  15082. (effort-minutes . org-duration-string-to-minutes))
  15083. nval)
  15084. (when (string= org-clock-current-task heading)
  15085. (setq org-clock-effort nval)
  15086. (org-clock-update-mode-line)))
  15087. (run-hook-with-args 'org-property-changed-functions key nval)))
  15088. (defun org-find-olp (path &optional this-buffer)
  15089. "Return a marker pointing to the entry at outline path OLP.
  15090. If anything goes wrong, throw an error.
  15091. You can wrap this call to catch the error like this:
  15092. (condition-case msg
  15093. (org-mobile-locate-entry (match-string 4))
  15094. (error (nth 1 msg)))
  15095. The return value will then be either a string with the error message,
  15096. or a marker if everything is OK.
  15097. If THIS-BUFFER is set, the outline path does not contain a file,
  15098. only headings."
  15099. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15100. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15101. (level 1)
  15102. (lmin 1)
  15103. (lmax 1)
  15104. limit re end found pos heading cnt flevel)
  15105. (unless buffer (error "File not found :%s" file))
  15106. (with-current-buffer buffer
  15107. (save-excursion
  15108. (save-restriction
  15109. (widen)
  15110. (setq limit (point-max))
  15111. (goto-char (point-min))
  15112. (dolist (heading path)
  15113. (setq re (format org-complex-heading-regexp-format
  15114. (regexp-quote heading)))
  15115. (setq cnt 0 pos (point))
  15116. (while (re-search-forward re end t)
  15117. (setq level (- (match-end 1) (match-beginning 1)))
  15118. (when (and (>= level lmin) (<= level lmax))
  15119. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15120. (when (= cnt 0) (error "Heading not found on level %d: %s"
  15121. lmax heading))
  15122. (when (> cnt 1) (error "Heading not unique on level %d: %s"
  15123. lmax heading))
  15124. (goto-char found)
  15125. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15126. (setq end (save-excursion (org-end-of-subtree t t))))
  15127. (when (org-at-heading-p)
  15128. (point-marker)))))))
  15129. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15130. "Find node HEADING in BUFFER.
  15131. Return a marker to the heading if it was found, or nil if not.
  15132. If POS-ONLY is set, return just the position instead of a marker.
  15133. The heading text must match exact, but it may have a TODO keyword,
  15134. a priority cookie and tags in the standard locations."
  15135. (with-current-buffer (or buffer (current-buffer))
  15136. (save-excursion
  15137. (save-restriction
  15138. (widen)
  15139. (goto-char (point-min))
  15140. (let (case-fold-search)
  15141. (when (re-search-forward
  15142. (format org-complex-heading-regexp-format
  15143. (regexp-quote heading)) nil t)
  15144. (if pos-only
  15145. (match-beginning 0)
  15146. (move-marker (make-marker) (match-beginning 0)))))))))
  15147. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15148. "Find Org node headline HEADING in all .org files in directory DIR.
  15149. When the target headline is found, return a marker to this location."
  15150. (let ((files (directory-files (or dir default-directory)
  15151. t "\\`[^.#].*\\.org\\'"))
  15152. visiting m buffer)
  15153. (catch 'found
  15154. (dolist (file files)
  15155. (message "trying %s" file)
  15156. (setq visiting (org-find-base-buffer-visiting file))
  15157. (setq buffer (or visiting (find-file-noselect file)))
  15158. (setq m (org-find-exact-headline-in-buffer
  15159. heading buffer))
  15160. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15161. (and m (throw 'found m))))))
  15162. (defun org-find-entry-with-id (ident)
  15163. "Locate the entry that contains the ID property with exact value IDENT.
  15164. IDENT can be a string, a symbol or a number, this function will search for
  15165. the string representation of it.
  15166. Return the position where this entry starts, or nil if there is no such entry."
  15167. (interactive "sID: ")
  15168. (let ((id (cond
  15169. ((stringp ident) ident)
  15170. ((symbolp ident) (symbol-name ident))
  15171. ((numberp ident) (number-to-string ident))
  15172. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15173. (org-with-wide-buffer (org-find-property "ID" id))))
  15174. ;;;; Timestamps
  15175. (defvar org-last-changed-timestamp nil)
  15176. (defvar org-last-inserted-timestamp nil
  15177. "The last time stamp inserted with `org-insert-time-stamp'.")
  15178. (defvar org-ts-what) ; dynamically scoped parameter
  15179. (defun org-time-stamp (arg &optional inactive)
  15180. "Prompt for a date/time and insert a time stamp.
  15181. If the user specifies a time like HH:MM or if this command is
  15182. called with at least one prefix argument, the time stamp contains
  15183. the date and the time. Otherwise, only the date is included.
  15184. All parts of a date not specified by the user are filled in from
  15185. the timestamp at point, if any, or the current date/time
  15186. otherwise.
  15187. If there is already a timestamp at the cursor, it is replaced.
  15188. With two universal prefix arguments, insert an active timestamp
  15189. with the current time without prompting the user.
  15190. When called from lisp, the timestamp is inactive if INACTIVE is
  15191. non-nil."
  15192. (interactive "P")
  15193. (let* ((ts (cond
  15194. ((org-at-date-range-p t)
  15195. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15196. ((org-at-timestamp-p t) (match-string 0))))
  15197. ;; Default time is either the timestamp at point or today.
  15198. ;; When entering a range, only the range start is considered.
  15199. (default-time (if (not ts) (current-time)
  15200. (apply #'encode-time (org-parse-time-string ts))))
  15201. (default-input (and ts (org-get-compact-tod ts)))
  15202. (repeater (and ts
  15203. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15204. (match-string 0 ts)))
  15205. org-time-was-given
  15206. org-end-time-was-given
  15207. (time
  15208. (and (if (equal arg '(16)) (current-time)
  15209. ;; Preserve `this-command' and `last-command'.
  15210. (let ((this-command this-command)
  15211. (last-command last-command))
  15212. (org-read-date
  15213. arg 'totime nil nil default-time default-input
  15214. inactive))))))
  15215. (cond
  15216. ((and ts
  15217. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15218. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15219. (insert "--")
  15220. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15221. (ts
  15222. ;; Make sure we're on a timestamp. When in the middle of a date
  15223. ;; range, move arbitrarily to range end.
  15224. (unless (org-at-timestamp-p t)
  15225. (skip-chars-forward "-")
  15226. (org-at-timestamp-p t))
  15227. (replace-match "")
  15228. (setq org-last-changed-timestamp
  15229. (org-insert-time-stamp
  15230. time (or org-time-was-given arg)
  15231. inactive nil nil (list org-end-time-was-given)))
  15232. (when repeater
  15233. (backward-char)
  15234. (insert " " repeater)
  15235. (setq org-last-changed-timestamp
  15236. (concat (substring org-last-inserted-timestamp 0 -1)
  15237. " " repeater ">")))
  15238. (message "Timestamp updated"))
  15239. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15240. (t (org-insert-time-stamp
  15241. time (or org-time-was-given arg) inactive nil nil
  15242. (list org-end-time-was-given))))))
  15243. ;; FIXME: can we use this for something else, like computing time differences?
  15244. (defun org-get-compact-tod (s)
  15245. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15246. (let* ((t1 (match-string 1 s))
  15247. (h1 (string-to-number (match-string 2 s)))
  15248. (m1 (string-to-number (match-string 3 s)))
  15249. (t2 (and (match-end 4) (match-string 5 s)))
  15250. (h2 (and t2 (string-to-number (match-string 6 s))))
  15251. (m2 (and t2 (string-to-number (match-string 7 s))))
  15252. dh dm)
  15253. (if (not t2)
  15254. t1
  15255. (setq dh (- h2 h1) dm (- m2 m1))
  15256. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15257. (concat t1 "+" (number-to-string dh)
  15258. (and (/= 0 dm) (format ":%02d" dm)))))))
  15259. (defun org-time-stamp-inactive (&optional arg)
  15260. "Insert an inactive time stamp.
  15261. An inactive time stamp is enclosed in square brackets instead of angle
  15262. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15263. does not link to the calendar and cannot be changed with the S-cursor keys.
  15264. So these are more for recording a certain time/date."
  15265. (interactive "P")
  15266. (org-time-stamp arg 'inactive))
  15267. (defvar org-date-ovl (make-overlay 1 1))
  15268. (overlay-put org-date-ovl 'face 'org-date-selected)
  15269. (org-detach-overlay org-date-ovl)
  15270. (defvar org-ans1) ; dynamically scoped parameter
  15271. (defvar org-ans2) ; dynamically scoped parameter
  15272. (defvar org-plain-time-of-day-regexp) ; defined below
  15273. (defvar org-overriding-default-time nil) ; dynamically scoped
  15274. (defvar org-read-date-overlay nil)
  15275. (defvar org-dcst nil) ; dynamically scoped
  15276. (defvar org-read-date-history nil)
  15277. (defvar org-read-date-final-answer nil)
  15278. (defvar org-read-date-analyze-futurep nil)
  15279. (defvar org-read-date-analyze-forced-year nil)
  15280. (defvar org-read-date-inactive)
  15281. (defvar org-read-date-minibuffer-local-map
  15282. (let* ((map (make-sparse-keymap)))
  15283. (set-keymap-parent map minibuffer-local-map)
  15284. (org-defkey map (kbd ".")
  15285. (lambda () (interactive)
  15286. ;; Are we at the beginning of the prompt?
  15287. (if (org-looking-back "^[^:]+: "
  15288. (let ((inhibit-field-text-motion t))
  15289. (line-beginning-position)))
  15290. (org-eval-in-calendar '(calendar-goto-today))
  15291. (insert "."))))
  15292. (org-defkey map (kbd "C-.")
  15293. (lambda () (interactive)
  15294. (org-eval-in-calendar '(calendar-goto-today))))
  15295. (org-defkey map [(meta shift left)]
  15296. (lambda () (interactive)
  15297. (org-eval-in-calendar '(calendar-backward-month 1))))
  15298. (org-defkey map [(meta shift right)]
  15299. (lambda () (interactive)
  15300. (org-eval-in-calendar '(calendar-forward-month 1))))
  15301. (org-defkey map [(meta shift up)]
  15302. (lambda () (interactive)
  15303. (org-eval-in-calendar '(calendar-backward-year 1))))
  15304. (org-defkey map [(meta shift down)]
  15305. (lambda () (interactive)
  15306. (org-eval-in-calendar '(calendar-forward-year 1))))
  15307. (org-defkey map [?\e (shift left)]
  15308. (lambda () (interactive)
  15309. (org-eval-in-calendar '(calendar-backward-month 1))))
  15310. (org-defkey map [?\e (shift right)]
  15311. (lambda () (interactive)
  15312. (org-eval-in-calendar '(calendar-forward-month 1))))
  15313. (org-defkey map [?\e (shift up)]
  15314. (lambda () (interactive)
  15315. (org-eval-in-calendar '(calendar-backward-year 1))))
  15316. (org-defkey map [?\e (shift down)]
  15317. (lambda () (interactive)
  15318. (org-eval-in-calendar '(calendar-forward-year 1))))
  15319. (org-defkey map [(shift up)]
  15320. (lambda () (interactive)
  15321. (org-eval-in-calendar '(calendar-backward-week 1))))
  15322. (org-defkey map [(shift down)]
  15323. (lambda () (interactive)
  15324. (org-eval-in-calendar '(calendar-forward-week 1))))
  15325. (org-defkey map [(shift left)]
  15326. (lambda () (interactive)
  15327. (org-eval-in-calendar '(calendar-backward-day 1))))
  15328. (org-defkey map [(shift right)]
  15329. (lambda () (interactive)
  15330. (org-eval-in-calendar '(calendar-forward-day 1))))
  15331. (org-defkey map "!"
  15332. (lambda () (interactive)
  15333. (org-eval-in-calendar '(diary-view-entries))
  15334. (message "")))
  15335. (org-defkey map ">"
  15336. (lambda () (interactive)
  15337. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15338. (org-defkey map "<"
  15339. (lambda () (interactive)
  15340. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15341. (org-defkey map "\C-v"
  15342. (lambda () (interactive)
  15343. (org-eval-in-calendar
  15344. '(calendar-scroll-left-three-months 1))))
  15345. (org-defkey map "\M-v"
  15346. (lambda () (interactive)
  15347. (org-eval-in-calendar
  15348. '(calendar-scroll-right-three-months 1))))
  15349. map)
  15350. "Keymap for minibuffer commands when using `org-read-date'.")
  15351. (defvar org-def)
  15352. (defvar org-defdecode)
  15353. (defvar org-with-time)
  15354. (defun org-read-date (&optional org-with-time to-time from-string prompt
  15355. default-time default-input inactive)
  15356. "Read a date, possibly a time, and make things smooth for the user.
  15357. The prompt will suggest to enter an ISO date, but you can also enter anything
  15358. which will at least partially be understood by `parse-time-string'.
  15359. Unrecognized parts of the date will default to the current day, month, year,
  15360. hour and minute. If this command is called to replace a timestamp at point,
  15361. or to enter the second timestamp of a range, the default time is taken
  15362. from the existing stamp. Furthermore, the command prefers the future,
  15363. so if you are giving a date where the year is not given, and the day-month
  15364. combination is already past in the current year, it will assume you
  15365. mean next year. For details, see the manual. A few examples:
  15366. 3-2-5 --> 2003-02-05
  15367. feb 15 --> currentyear-02-15
  15368. 2/15 --> currentyear-02-15
  15369. sep 12 9 --> 2009-09-12
  15370. 12:45 --> today 12:45
  15371. 22 sept 0:34 --> currentyear-09-22 0:34
  15372. 12 --> currentyear-currentmonth-12
  15373. Fri --> nearest Friday after today
  15374. -Tue --> last Tuesday
  15375. etc.
  15376. Furthermore you can specify a relative date by giving, as the *first* thing
  15377. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15378. change in days weeks, months, years.
  15379. With a single plus or minus, the date is relative to today. With a double
  15380. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15381. +4d --> four days from today
  15382. +4 --> same as above
  15383. +2w --> two weeks from today
  15384. ++5 --> five days from default date
  15385. The function understands only English month and weekday abbreviations.
  15386. While prompting, a calendar is popped up - you can also select the
  15387. date with the mouse (button 1). The calendar shows a period of three
  15388. months. To scroll it to other months, use the keys `>' and `<'.
  15389. If you don't like the calendar, turn it off with
  15390. (setq org-read-date-popup-calendar nil)
  15391. With optional argument TO-TIME, the date will immediately be converted
  15392. to an internal time.
  15393. With an optional argument ORG-WITH-TIME, the prompt will suggest to
  15394. also insert a time. Note that when ORG-WITH-TIME is not set, you can
  15395. still enter a time, and this function will inform the calling routine
  15396. about this change. The calling routine may then choose to change the
  15397. format used to insert the time stamp into the buffer to include the time.
  15398. With optional argument FROM-STRING, read from this string instead from
  15399. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15400. the time/date that is used for everything that is not specified by the
  15401. user."
  15402. (require 'parse-time)
  15403. (let* ((org-time-stamp-rounding-minutes
  15404. (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
  15405. (org-dcst org-display-custom-times)
  15406. (ct (org-current-time))
  15407. (org-def (or org-overriding-default-time default-time ct))
  15408. (org-defdecode (decode-time org-def))
  15409. (dummy (progn
  15410. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15411. (setcar (nthcdr 2 org-defdecode) -1)
  15412. (setcar (nthcdr 1 org-defdecode) 59)
  15413. (setq org-def (apply 'encode-time org-defdecode)
  15414. org-defdecode (decode-time org-def)))))
  15415. (cur-frame (selected-frame))
  15416. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15417. (calendar-frame-setup nil)
  15418. (calendar-setup (when (eq calendar-setup 'calendar-only) 'calendar-only))
  15419. (calendar-move-hook nil)
  15420. (calendar-view-diary-initially-flag nil)
  15421. (calendar-view-holidays-initially-flag nil)
  15422. (timestr (format-time-string
  15423. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
  15424. (prompt (concat (if prompt (concat prompt " ") "")
  15425. (format "Date+time [%s]: " timestr)))
  15426. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15427. (cond
  15428. (from-string (setq ans from-string))
  15429. (org-read-date-popup-calendar
  15430. (save-excursion
  15431. (save-window-excursion
  15432. (calendar)
  15433. (when (eq calendar-setup 'calendar-only)
  15434. (setq cal-frame
  15435. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15436. (select-frame cal-frame))
  15437. (org-eval-in-calendar '(setq cursor-type nil) t)
  15438. (unwind-protect
  15439. (progn
  15440. (calendar-forward-day (- (time-to-days org-def)
  15441. (calendar-absolute-from-gregorian
  15442. (calendar-current-date))))
  15443. (org-eval-in-calendar nil t)
  15444. (let* ((old-map (current-local-map))
  15445. (map (copy-keymap calendar-mode-map))
  15446. (minibuffer-local-map
  15447. (copy-keymap org-read-date-minibuffer-local-map)))
  15448. (org-defkey map (kbd "RET") 'org-calendar-select)
  15449. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15450. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15451. (unwind-protect
  15452. (progn
  15453. (use-local-map map)
  15454. (setq org-read-date-inactive inactive)
  15455. (add-hook 'post-command-hook 'org-read-date-display)
  15456. (setq org-ans0 (read-string prompt default-input
  15457. 'org-read-date-history nil))
  15458. ;; org-ans0: from prompt
  15459. ;; org-ans1: from mouse click
  15460. ;; org-ans2: from calendar motion
  15461. (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
  15462. (remove-hook 'post-command-hook 'org-read-date-display)
  15463. (use-local-map old-map)
  15464. (when org-read-date-overlay
  15465. (delete-overlay org-read-date-overlay)
  15466. (setq org-read-date-overlay nil)))))
  15467. (bury-buffer "*Calendar*")
  15468. (when cal-frame
  15469. (delete-frame cal-frame)
  15470. (select-frame-set-input-focus cur-frame))))))
  15471. (t ; Naked prompt only
  15472. (unwind-protect
  15473. (setq ans (read-string prompt default-input
  15474. 'org-read-date-history timestr))
  15475. (when org-read-date-overlay
  15476. (delete-overlay org-read-date-overlay)
  15477. (setq org-read-date-overlay nil)))))
  15478. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15479. (when org-read-date-analyze-forced-year
  15480. (message "Year was forced into %s"
  15481. (if org-read-date-force-compatible-dates
  15482. "compatible range (1970-2037)"
  15483. "range representable on this machine"))
  15484. (ding))
  15485. ;; One round trip to get rid of 34th of August and stuff like that....
  15486. (setq final (decode-time (apply 'encode-time final)))
  15487. (setq org-read-date-final-answer ans)
  15488. (if to-time
  15489. (apply 'encode-time final)
  15490. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15491. (format "%04d-%02d-%02d %02d:%02d"
  15492. (nth 5 final) (nth 4 final) (nth 3 final)
  15493. (nth 2 final) (nth 1 final))
  15494. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15495. (defun org-read-date-display ()
  15496. "Display the current date prompt interpretation in the minibuffer."
  15497. (when org-read-date-display-live
  15498. (when org-read-date-overlay
  15499. (delete-overlay org-read-date-overlay))
  15500. (when (minibufferp (current-buffer))
  15501. (save-excursion
  15502. (end-of-line 1)
  15503. (while (not (equal (buffer-substring
  15504. (max (point-min) (- (point) 4)) (point))
  15505. " "))
  15506. (insert " ")))
  15507. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15508. " " (or org-ans1 org-ans2)))
  15509. (org-end-time-was-given nil)
  15510. (f (org-read-date-analyze ans org-def org-defdecode))
  15511. (fmts (if org-dcst
  15512. org-time-stamp-custom-formats
  15513. org-time-stamp-formats))
  15514. (fmt (if (or org-with-time
  15515. (and (boundp 'org-time-was-given) org-time-was-given))
  15516. (cdr fmts)
  15517. (car fmts)))
  15518. (txt (format-time-string fmt (apply 'encode-time f)))
  15519. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15520. (txt (concat "=> " txt)))
  15521. (when (and org-end-time-was-given
  15522. (string-match org-plain-time-of-day-regexp txt))
  15523. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15524. org-end-time-was-given
  15525. (substring txt (match-end 0)))))
  15526. (when org-read-date-analyze-futurep
  15527. (setq txt (concat txt " (=>F)")))
  15528. (setq org-read-date-overlay
  15529. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15530. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15531. (defun org-read-date-analyze (ans org-def org-defdecode)
  15532. "Analyze the combined answer of the date prompt."
  15533. ;; FIXME: cleanup and comment
  15534. ;; Pass `current-time' result to `decode-time' (instead of calling
  15535. ;; without arguments) so that only `current-time' has to be
  15536. ;; overriden in tests.
  15537. (let ((nowdecode (decode-time (current-time)))
  15538. delta deltan deltaw deltadef year month day
  15539. hour minute second wday pm h2 m2 tl wday1
  15540. iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
  15541. (setq org-read-date-analyze-futurep nil
  15542. org-read-date-analyze-forced-year nil)
  15543. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15544. (setq ans "+0"))
  15545. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15546. (setq ans (replace-match "" t t ans)
  15547. deltan (car delta)
  15548. deltaw (nth 1 delta)
  15549. deltadef (nth 2 delta)))
  15550. ;; Check if there is an iso week date in there. If yes, store the
  15551. ;; info and postpone interpreting it until the rest of the parsing
  15552. ;; is done.
  15553. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15554. (setq iso-year (when (match-end 1)
  15555. (org-small-year-to-year
  15556. (string-to-number (match-string 1 ans))))
  15557. iso-weekday (when (match-end 3)
  15558. (string-to-number (match-string 3 ans)))
  15559. iso-week (string-to-number (match-string 2 ans)))
  15560. (setq ans (replace-match "" t t ans)))
  15561. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15562. (when (string-match
  15563. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15564. (setq year (if (match-end 2)
  15565. (string-to-number (match-string 2 ans))
  15566. (progn (setq kill-year t)
  15567. (string-to-number (format-time-string "%Y"))))
  15568. month (string-to-number (match-string 3 ans))
  15569. day (string-to-number (match-string 4 ans)))
  15570. (when (< year 100) (setq year (+ 2000 year)))
  15571. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15572. t nil ans)))
  15573. ;; Help matching dotted european dates
  15574. (when (string-match
  15575. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15576. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15577. (setq kill-year t)
  15578. (string-to-number (format-time-string "%Y")))
  15579. day (string-to-number (match-string 1 ans))
  15580. month (string-to-number (match-string 2 ans))
  15581. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15582. t nil ans)))
  15583. ;; Help matching american dates, like 5/30 or 5/30/7
  15584. (when (string-match
  15585. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15586. (setq year (if (match-end 4)
  15587. (string-to-number (match-string 4 ans))
  15588. (progn (setq kill-year t)
  15589. (string-to-number (format-time-string "%Y"))))
  15590. month (string-to-number (match-string 1 ans))
  15591. day (string-to-number (match-string 2 ans)))
  15592. (when (< year 100) (setq year (+ 2000 year)))
  15593. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15594. t nil ans)))
  15595. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15596. ;; If there is a time with am/pm, and *no* time without it, we convert
  15597. ;; so that matching will be successful.
  15598. (loop for i from 1 to 2 do ; twice, for end time as well
  15599. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15600. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15601. (setq hour (string-to-number (match-string 1 ans))
  15602. minute (if (match-end 3)
  15603. (string-to-number (match-string 3 ans))
  15604. 0)
  15605. pm (equal ?p
  15606. (string-to-char (downcase (match-string 4 ans)))))
  15607. (if (and (= hour 12) (not pm))
  15608. (setq hour 0)
  15609. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15610. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15611. t t ans))))
  15612. ;; Check if a time range is given as a duration
  15613. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15614. (setq hour (string-to-number (match-string 1 ans))
  15615. h2 (+ hour (string-to-number (match-string 3 ans)))
  15616. minute (string-to-number (match-string 2 ans))
  15617. m2 (+ minute (if (match-end 5) (string-to-number
  15618. (match-string 5 ans))0)))
  15619. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15620. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15621. t t ans)))
  15622. ;; Check if there is a time range
  15623. (when (boundp 'org-end-time-was-given)
  15624. (setq org-time-was-given nil)
  15625. (when (and (string-match org-plain-time-of-day-regexp ans)
  15626. (match-end 8))
  15627. (setq org-end-time-was-given (match-string 8 ans))
  15628. (setq ans (concat (substring ans 0 (match-beginning 7))
  15629. (substring ans (match-end 7))))))
  15630. (setq tl (parse-time-string ans)
  15631. day (or (nth 3 tl) (nth 3 org-defdecode))
  15632. month
  15633. (cond ((nth 4 tl))
  15634. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15635. ;; Day was specified. Make sure DAY+MONTH
  15636. ;; combination happens in the future.
  15637. ((nth 3 tl)
  15638. (setq futurep t)
  15639. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15640. (nth 4 nowdecode)))
  15641. (t (nth 4 org-defdecode)))
  15642. year
  15643. (cond ((and (not kill-year) (nth 5 tl)))
  15644. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15645. ;; Month was guessed in the future and is at least
  15646. ;; equal to NOWDECODE's. Fix year accordingly.
  15647. (futurep
  15648. (if (or (> month (nth 4 nowdecode))
  15649. (>= day (nth 3 nowdecode)))
  15650. (nth 5 nowdecode)
  15651. (1+ (nth 5 nowdecode))))
  15652. ;; Month was specified. Make sure MONTH+YEAR
  15653. ;; combination happens in the future.
  15654. ((nth 4 tl)
  15655. (setq futurep t)
  15656. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15657. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15658. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15659. (t (nth 5 nowdecode))))
  15660. (t (nth 5 org-defdecode)))
  15661. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15662. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15663. second (or (nth 0 tl) 0)
  15664. wday (nth 6 tl))
  15665. (when (and (eq org-read-date-prefer-future 'time)
  15666. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15667. (equal day (nth 3 nowdecode))
  15668. (equal month (nth 4 nowdecode))
  15669. (equal year (nth 5 nowdecode))
  15670. (nth 2 tl)
  15671. (or (< (nth 2 tl) (nth 2 nowdecode))
  15672. (and (= (nth 2 tl) (nth 2 nowdecode))
  15673. (nth 1 tl)
  15674. (< (nth 1 tl) (nth 1 nowdecode)))))
  15675. (setq day (1+ day)
  15676. futurep t))
  15677. ;; Special date definitions below
  15678. (cond
  15679. (iso-week
  15680. ;; There was an iso week
  15681. (require 'cal-iso)
  15682. (setq futurep nil)
  15683. (setq year (or iso-year year)
  15684. day (or iso-weekday wday 1)
  15685. wday nil ; to make sure that the trigger below does not match
  15686. iso-date (calendar-gregorian-from-absolute
  15687. (calendar-iso-to-absolute
  15688. (list iso-week day year))))
  15689. ; FIXME: Should we also push ISO weeks into the future?
  15690. ; (when (and org-read-date-prefer-future
  15691. ; (not iso-year)
  15692. ; (< (calendar-absolute-from-gregorian iso-date)
  15693. ; (time-to-days (current-time))))
  15694. ; (setq year (1+ year)
  15695. ; iso-date (calendar-gregorian-from-absolute
  15696. ; (calendar-iso-to-absolute
  15697. ; (list iso-week day year)))))
  15698. (setq month (car iso-date)
  15699. year (nth 2 iso-date)
  15700. day (nth 1 iso-date)))
  15701. (deltan
  15702. (setq futurep nil)
  15703. (unless deltadef
  15704. ;; Pass `current-time' result to `decode-time' (instead of
  15705. ;; calling without arguments) so that only `current-time' has
  15706. ;; to be overriden in tests.
  15707. (let ((now (decode-time (current-time))))
  15708. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15709. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15710. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15711. ((equal deltaw "m") (setq month (+ month deltan)))
  15712. ((equal deltaw "y") (setq year (+ year deltan)))))
  15713. ((and wday (not (nth 3 tl)))
  15714. ;; Weekday was given, but no day, so pick that day in the week
  15715. ;; on or after the derived date.
  15716. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15717. (unless (equal wday wday1)
  15718. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15719. (when (and (boundp 'org-time-was-given)
  15720. (nth 2 tl))
  15721. (setq org-time-was-given t))
  15722. (when (< year 100) (setq year (+ 2000 year)))
  15723. ;; Check of the date is representable
  15724. (if org-read-date-force-compatible-dates
  15725. (progn
  15726. (when (< year 1970)
  15727. (setq year 1970 org-read-date-analyze-forced-year t))
  15728. (when (> year 2037)
  15729. (setq year 2037 org-read-date-analyze-forced-year t)))
  15730. (condition-case nil
  15731. (ignore (encode-time second minute hour day month year))
  15732. (error
  15733. (setq year (nth 5 org-defdecode))
  15734. (setq org-read-date-analyze-forced-year t))))
  15735. (setq org-read-date-analyze-futurep futurep)
  15736. (list second minute hour day month year)))
  15737. (defvar parse-time-weekdays)
  15738. (defun org-read-date-get-relative (s today default)
  15739. "Check string S for special relative date string.
  15740. TODAY and DEFAULT are internal times, for today and for a default.
  15741. Return shift list (N what def-flag)
  15742. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15743. N is the number of WHATs to shift.
  15744. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15745. the DEFAULT date rather than TODAY."
  15746. (require 'parse-time)
  15747. (when (and
  15748. (string-match
  15749. (concat
  15750. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15751. "\\([0-9]+\\)?"
  15752. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15753. "\\([ \t]\\|$\\)") s)
  15754. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15755. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15756. (string-to-char (substring (match-string 1 s) -1))
  15757. ?+))
  15758. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15759. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15760. (what (if (match-end 3) (match-string 3 s) "d"))
  15761. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15762. (date (if rel default today))
  15763. (wday (nth 6 (decode-time date)))
  15764. delta)
  15765. (if wday1
  15766. (progn
  15767. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15768. (when (= delta 0) (setq delta 7))
  15769. (when (= dir ?-)
  15770. (setq delta (- delta 7))
  15771. (when (= delta 0) (setq delta -7)))
  15772. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15773. (list delta "d" rel))
  15774. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15775. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15776. "Turn a user-specified date into the internal representation.
  15777. The internal representation needed by the calendar is (month day year).
  15778. This is a wrapper to handle the brain-dead convention in calendar that
  15779. user function argument order change dependent on argument order."
  15780. (if (boundp 'calendar-date-style)
  15781. (cond
  15782. ((eq calendar-date-style 'american)
  15783. (list arg1 arg2 arg3))
  15784. ((eq calendar-date-style 'european)
  15785. (list arg2 arg1 arg3))
  15786. ((eq calendar-date-style 'iso)
  15787. (list arg2 arg3 arg1)))
  15788. (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
  15789. (if (org-bound-and-true-p european-calendar-style)
  15790. (list arg2 arg1 arg3)
  15791. (list arg1 arg2 arg3)))))
  15792. (defun org-eval-in-calendar (form &optional keepdate)
  15793. "Eval FORM in the calendar window and return to current window.
  15794. When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
  15795. otherwise stick to the current value of `org-ans2'."
  15796. (let ((sf (selected-frame))
  15797. (sw (selected-window)))
  15798. (select-window (get-buffer-window "*Calendar*" t))
  15799. (eval form)
  15800. (when (and (not keepdate) (calendar-cursor-to-date))
  15801. (let* ((date (calendar-cursor-to-date))
  15802. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15803. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15804. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15805. (select-window sw)
  15806. (org-select-frame-set-input-focus sf)))
  15807. (defun org-calendar-select ()
  15808. "Return to `org-read-date' with the date currently selected.
  15809. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15810. (interactive)
  15811. (when (calendar-cursor-to-date)
  15812. (let* ((date (calendar-cursor-to-date))
  15813. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15814. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15815. (when (active-minibuffer-window) (exit-minibuffer))))
  15816. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15817. "Insert a date stamp for the date given by the internal TIME.
  15818. See `format-time-string' for the format of TIME.
  15819. WITH-HM means use the stamp format that includes the time of the day.
  15820. INACTIVE means use square brackets instead of angular ones, so that the
  15821. stamp will not contribute to the agenda.
  15822. PRE and POST are optional strings to be inserted before and after the
  15823. stamp.
  15824. The command returns the inserted time stamp."
  15825. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15826. stamp)
  15827. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15828. (insert-before-markers (or pre ""))
  15829. (when (listp extra)
  15830. (setq extra (car extra))
  15831. (if (and (stringp extra)
  15832. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15833. (setq extra (format "-%02d:%02d"
  15834. (string-to-number (match-string 1 extra))
  15835. (string-to-number (match-string 2 extra))))
  15836. (setq extra nil)))
  15837. (when extra
  15838. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15839. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15840. (insert-before-markers (or post ""))
  15841. (setq org-last-inserted-timestamp stamp)))
  15842. (defun org-toggle-time-stamp-overlays ()
  15843. "Toggle the use of custom time stamp formats."
  15844. (interactive)
  15845. (setq org-display-custom-times (not org-display-custom-times))
  15846. (unless org-display-custom-times
  15847. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15848. (while (setq p (next-single-property-change p 'display))
  15849. (when (and (get-text-property p 'display)
  15850. (eq (get-text-property p 'face) 'org-date))
  15851. (remove-text-properties
  15852. p (setq p (next-single-property-change p 'display))
  15853. '(display t))))
  15854. (set-buffer-modified-p bmp)))
  15855. (when (featurep 'xemacs)
  15856. (remove-text-properties (point-min) (point-max) '(end-glyph t)))
  15857. (org-restart-font-lock)
  15858. (setq org-table-may-need-update t)
  15859. (if org-display-custom-times
  15860. (message "Time stamps are overlaid with custom format")
  15861. (message "Time stamp overlays removed")))
  15862. (defun org-display-custom-time (beg end)
  15863. "Overlay modified time stamp format over timestamp between BEG and END."
  15864. (let* ((ts (buffer-substring beg end))
  15865. t1 w1 with-hm tf time str w2 (off 0))
  15866. (save-match-data
  15867. (setq t1 (org-parse-time-string ts t))
  15868. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15869. (setq off (- (match-end 0) (match-beginning 0)))))
  15870. (setq end (- end off))
  15871. (setq w1 (- end beg)
  15872. with-hm (and (nth 1 t1) (nth 2 t1))
  15873. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15874. time (org-fix-decoded-time t1)
  15875. str (org-add-props
  15876. (format-time-string
  15877. (substring tf 1 -1) (apply 'encode-time time))
  15878. nil 'mouse-face 'highlight)
  15879. w2 (length str))
  15880. (unless (= w2 w1)
  15881. (add-text-properties (1+ beg) (+ 2 beg)
  15882. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15883. (if (featurep 'xemacs)
  15884. (progn
  15885. (put-text-property beg end 'invisible t)
  15886. (put-text-property beg end 'end-glyph (make-glyph str)))
  15887. (put-text-property beg end 'display str))))
  15888. (defun org-fix-decoded-time (time)
  15889. "Set 0 instead of nil for the first 6 elements of time.
  15890. Don't touch the rest."
  15891. (let ((n 0))
  15892. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15893. (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
  15894. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15895. "Difference between TIMESTAMP-STRING and now in days.
  15896. If SECONDS is non-nil, return the difference in seconds."
  15897. (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
  15898. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15899. (funcall fdiff (current-time)))))
  15900. (defun org-deadline-close (timestamp-string &optional ndays)
  15901. "Is the time in TIMESTAMP-STRING close to the current date?"
  15902. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15903. (and (< (org-time-stamp-to-now timestamp-string) ndays)
  15904. (not (org-entry-is-done-p))))
  15905. (defun org-get-wdays (ts &optional delay zero-delay)
  15906. "Get the deadline lead time appropriate for timestring TS.
  15907. When DELAY is non-nil, get the delay time for scheduled items
  15908. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15909. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15910. don't try to find the delay cookie in the scheduled timestamp."
  15911. (let ((tv (if delay org-scheduled-delay-days
  15912. org-deadline-warning-days)))
  15913. (cond
  15914. ((or (and delay (< tv 0))
  15915. (and delay zero-delay (<= tv 0))
  15916. (and (not delay) (<= tv 0)))
  15917. ;; Enforce this value no matter what
  15918. (- tv))
  15919. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15920. ;; lead time is specified.
  15921. (floor (* (string-to-number (match-string 1 ts))
  15922. (cdr (assoc (match-string 2 ts)
  15923. '(("d" . 1) ("w" . 7)
  15924. ("m" . 30.4) ("y" . 365.25)
  15925. ("h" . 0.041667)))))))
  15926. ;; go for the default.
  15927. (t tv))))
  15928. (defun org-calendar-select-mouse (ev)
  15929. "Return to `org-read-date' with the date currently selected.
  15930. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15931. (interactive "e")
  15932. (mouse-set-point ev)
  15933. (when (calendar-cursor-to-date)
  15934. (let* ((date (calendar-cursor-to-date))
  15935. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15936. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15937. (when (active-minibuffer-window) (exit-minibuffer))))
  15938. (defun org-check-deadlines (ndays)
  15939. "Check if there are any deadlines due or past due.
  15940. A deadline is considered due if it happens within `org-deadline-warning-days'
  15941. days from today's date. If the deadline appears in an entry marked DONE,
  15942. it is not shown. The prefix arg NDAYS can be used to test that many
  15943. days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
  15944. (interactive "P")
  15945. (let* ((org-warn-days
  15946. (cond
  15947. ((equal ndays '(4)) 100000)
  15948. (ndays (prefix-numeric-value ndays))
  15949. (t (abs org-deadline-warning-days))))
  15950. (case-fold-search nil)
  15951. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15952. (callback
  15953. (lambda () (org-deadline-close (match-string 1) org-warn-days))))
  15954. (message "%d deadlines past-due or due within %d days"
  15955. (org-occur regexp nil callback)
  15956. org-warn-days)))
  15957. (defsubst org-re-timestamp (type)
  15958. "Return a regexp for timestamp TYPE.
  15959. Allowed values for TYPE are:
  15960. all: all timestamps
  15961. active: only active timestamps (<...>)
  15962. inactive: only inactive timestamps ([...])
  15963. scheduled: only scheduled timestamps
  15964. deadline: only deadline timestamps
  15965. closed: only closed time-stamps
  15966. When TYPE is nil, fall back on returning a regexp that matches
  15967. both scheduled and deadline timestamps."
  15968. (case type
  15969. (all org-ts-regexp-both)
  15970. (active org-ts-regexp)
  15971. (inactive org-ts-regexp-inactive)
  15972. (scheduled org-scheduled-time-regexp)
  15973. (deadline org-deadline-time-regexp)
  15974. (closed org-closed-time-regexp)
  15975. (otherwise
  15976. (concat "\\<"
  15977. (regexp-opt (list org-deadline-string org-scheduled-string))
  15978. " *<\\([^>]+\\)>"))))
  15979. (defun org-check-before-date (date)
  15980. "Check if there are deadlines or scheduled entries before DATE."
  15981. (interactive (list (org-read-date)))
  15982. (let ((case-fold-search nil)
  15983. (regexp (org-re-timestamp org-ts-type))
  15984. (callback
  15985. `(lambda ()
  15986. (let ((match (match-string 1)))
  15987. (and ,(if (memq org-ts-type '(active inactive all))
  15988. '(eq (org-element-type (org-element-context)) 'timestamp)
  15989. '(org-at-planning-p))
  15990. (time-less-p
  15991. (org-time-string-to-time match)
  15992. (org-time-string-to-time date)))))))
  15993. (message "%d entries before %s"
  15994. (org-occur regexp nil callback) date)))
  15995. (defun org-check-after-date (date)
  15996. "Check if there are deadlines or scheduled entries after DATE."
  15997. (interactive (list (org-read-date)))
  15998. (let ((case-fold-search nil)
  15999. (regexp (org-re-timestamp org-ts-type))
  16000. (callback
  16001. `(lambda ()
  16002. (let ((match (match-string 1)))
  16003. (and ,(if (memq org-ts-type '(active inactive all))
  16004. '(eq (org-element-type (org-element-context)) 'timestamp)
  16005. '(org-at-planning-p))
  16006. (not (time-less-p
  16007. (org-time-string-to-time match)
  16008. (org-time-string-to-time date))))))))
  16009. (message "%d entries after %s"
  16010. (org-occur regexp nil callback) date)))
  16011. (defun org-check-dates-range (start-date end-date)
  16012. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16013. (interactive (list (org-read-date nil nil nil "Range starts")
  16014. (org-read-date nil nil nil "Range end")))
  16015. (let ((case-fold-search nil)
  16016. (regexp (org-re-timestamp org-ts-type))
  16017. (callback
  16018. `(lambda ()
  16019. (let ((match (match-string 1)))
  16020. (and
  16021. ,(if (memq org-ts-type '(active inactive all))
  16022. '(eq (org-element-type (org-element-context)) 'timestamp)
  16023. '(org-at-planning-p))
  16024. (not (time-less-p
  16025. (org-time-string-to-time match)
  16026. (org-time-string-to-time start-date)))
  16027. (time-less-p
  16028. (org-time-string-to-time match)
  16029. (org-time-string-to-time end-date)))))))
  16030. (message "%d entries between %s and %s"
  16031. (org-occur regexp nil callback) start-date end-date)))
  16032. (defun org-evaluate-time-range (&optional to-buffer)
  16033. "Evaluate a time range by computing the difference between start and end.
  16034. Normally the result is just printed in the echo area, but with prefix arg
  16035. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16036. If the time range is actually in a table, the result is inserted into the
  16037. next column.
  16038. For time difference computation, a year is assumed to be exactly 365
  16039. days in order to avoid rounding problems."
  16040. (interactive "P")
  16041. (or
  16042. (org-clock-update-time-maybe)
  16043. (save-excursion
  16044. (unless (org-at-date-range-p t)
  16045. (goto-char (point-at-bol))
  16046. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16047. (unless (org-at-date-range-p t)
  16048. (user-error "Not at a time-stamp range, and none found in current line")))
  16049. (let* ((ts1 (match-string 1))
  16050. (ts2 (match-string 2))
  16051. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16052. (match-end (match-end 0))
  16053. (time1 (org-time-string-to-time ts1))
  16054. (time2 (org-time-string-to-time ts2))
  16055. (t1 (org-float-time time1))
  16056. (t2 (org-float-time time2))
  16057. (diff (abs (- t2 t1)))
  16058. (negative (< (- t2 t1) 0))
  16059. ;; (ys (floor (* 365 24 60 60)))
  16060. (ds (* 24 60 60))
  16061. (hs (* 60 60))
  16062. (fy "%dy %dd %02d:%02d")
  16063. (fy1 "%dy %dd")
  16064. (fd "%dd %02d:%02d")
  16065. (fd1 "%dd")
  16066. (fh "%02d:%02d")
  16067. y d h m align)
  16068. (if havetime
  16069. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16070. y 0
  16071. d (floor (/ diff ds)) diff (mod diff ds)
  16072. h (floor (/ diff hs)) diff (mod diff hs)
  16073. m (floor (/ diff 60)))
  16074. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16075. y 0
  16076. d (floor (+ (/ diff ds) 0.5))
  16077. h 0 m 0))
  16078. (if (not to-buffer)
  16079. (message "%s" (org-make-tdiff-string y d h m))
  16080. (if (org-at-table-p)
  16081. (progn
  16082. (goto-char match-end)
  16083. (setq align t)
  16084. (and (looking-at " *|") (goto-char (match-end 0))))
  16085. (goto-char match-end))
  16086. (when (looking-at
  16087. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16088. (replace-match ""))
  16089. (when negative (insert " -"))
  16090. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16091. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16092. (insert " " (format fh h m))))
  16093. (when align (org-table-align))
  16094. (message "Time difference inserted")))))
  16095. (defun org-make-tdiff-string (y d h m)
  16096. (let ((fmt "")
  16097. (l nil))
  16098. (when (> y 0)
  16099. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16100. (push y l))
  16101. (when (> d 0)
  16102. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16103. (push d l))
  16104. (when (> h 0)
  16105. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16106. (push h l))
  16107. (when (> m 0)
  16108. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16109. (push m l))
  16110. (apply 'format fmt (nreverse l))))
  16111. (defun org-time-string-to-time (s &optional buffer pos)
  16112. "Convert a timestamp string into internal time."
  16113. (condition-case errdata
  16114. (apply 'encode-time (org-parse-time-string s))
  16115. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16116. s (if (not (and buffer pos))
  16117. ""
  16118. (format-message " at %d in buffer `%s'" pos buffer))
  16119. (cdr errdata)))))
  16120. (defun org-time-string-to-seconds (s)
  16121. "Convert a timestamp string to a number of seconds."
  16122. (org-float-time (org-time-string-to-time s)))
  16123. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16124. (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
  16125. "Convert time stamp S to an absolute day number.
  16126. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16127. stamp, get the closest date to DAYNR. If PREFER is
  16128. `past' (respectively `future') return a date past (respectively
  16129. after) or equal to DAYNR.
  16130. POS is the location of time stamp S, as a buffer position in
  16131. BUFFER.
  16132. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16133. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16134. signalled."
  16135. (cond
  16136. ((string-match "\\`%%\\((.*)\\)" s)
  16137. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16138. ;; only able to match individual dates. If it fails, raise an
  16139. ;; error.
  16140. (if (and daynr
  16141. (org-diary-sexp-entry
  16142. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16143. daynr
  16144. (signal 'org-diary-sexp-no-match (list s))))
  16145. ((and daynr show-all) (org-closest-date s daynr prefer))
  16146. (t (time-to-days
  16147. (condition-case errdata
  16148. (apply #'encode-time (org-parse-time-string s))
  16149. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16150. s
  16151. (if (not (and buffer pos)) ""
  16152. (format-message " at %d in buffer `%s'" pos buffer))
  16153. (cdr errdata))))))))
  16154. (defun org-days-to-iso-week (days)
  16155. "Return the iso week number."
  16156. (require 'cal-iso)
  16157. (car (calendar-iso-from-absolute days)))
  16158. (defun org-small-year-to-year (year)
  16159. "Convert 2-digit years into 4-digit years.
  16160. YEAR is expanded into one of the 30 next years, if possible, or
  16161. into a past one. Any year larger than 99 is returned unchanged."
  16162. (if (>= year 100) year
  16163. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16164. (century (/ current 100))
  16165. (offset (- year (% current 100))))
  16166. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16167. ((> offset -70) (+ (* century 100) year))
  16168. (t (+ (* (1+ century) 100) year))))))
  16169. (defun org-time-from-absolute (d)
  16170. "Return the time corresponding to date D.
  16171. D may be an absolute day number, or a calendar-type list (month day year)."
  16172. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16173. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16174. (defun org-calendar-holiday ()
  16175. "List of holidays, for Diary display in Org-mode."
  16176. (require 'holidays)
  16177. (let ((hl (funcall
  16178. (if (fboundp 'calendar-check-holidays)
  16179. 'calendar-check-holidays 'check-calendar-holidays) date)))
  16180. (when hl (mapconcat 'identity hl "; "))))
  16181. (defun org-diary-sexp-entry (sexp entry date)
  16182. "Process a SEXP diary ENTRY for DATE."
  16183. (require 'diary-lib)
  16184. (let ((result (if calendar-debug-sexp
  16185. (let ((stack-trace-on-error t))
  16186. (eval (car (read-from-string sexp))))
  16187. (condition-case nil
  16188. (eval (car (read-from-string sexp)))
  16189. (error
  16190. (beep)
  16191. (message "Bad sexp at line %d in %s: %s"
  16192. (org-current-line)
  16193. (buffer-file-name) sexp)
  16194. (sleep-for 2))))))
  16195. (cond ((stringp result) (split-string result "; "))
  16196. ((and (consp result)
  16197. (not (consp (cdr result)))
  16198. (stringp (cdr result))) (cdr result))
  16199. ((and (consp result)
  16200. (stringp (car result))) result)
  16201. (result entry))))
  16202. (defun org-diary-to-ical-string (frombuf)
  16203. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16204. This uses the icalendar.el library."
  16205. (let* ((tmpdir (if (featurep 'xemacs)
  16206. (temp-directory)
  16207. temporary-file-directory))
  16208. (tmpfile (make-temp-name
  16209. (expand-file-name "orgics" tmpdir)))
  16210. buf rtn b e)
  16211. (with-current-buffer frombuf
  16212. (icalendar-export-region (point-min) (point-max) tmpfile)
  16213. (setq buf (find-buffer-visiting tmpfile))
  16214. (set-buffer buf)
  16215. (goto-char (point-min))
  16216. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16217. (setq b (match-beginning 0)))
  16218. (goto-char (point-max))
  16219. (when (re-search-backward "^END:VEVENT" nil t)
  16220. (setq e (match-end 0)))
  16221. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16222. (kill-buffer buf)
  16223. (delete-file tmpfile)
  16224. rtn))
  16225. (defun org-closest-date (start current prefer)
  16226. "Return closest date to CURRENT starting from START.
  16227. CURRENT and START are both time stamps.
  16228. When PREFER is `past', return a date that is either CURRENT or
  16229. past. When PREFER is `future', return a date that is either
  16230. CURRENT or future.
  16231. Only time stamps with a repeater are modified. Any other time
  16232. stamp stay unchanged. In any case, return value is an absolute
  16233. day number."
  16234. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16235. ;; No repeater. Do not shift time stamp.
  16236. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16237. (let ((value (string-to-number (match-string 1 start)))
  16238. (type (match-string 2 start)))
  16239. (if (= 0 value)
  16240. ;; Repeater with a 0-value is considered as void.
  16241. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16242. (let* ((base (org-date-to-gregorian start))
  16243. (target (org-date-to-gregorian current))
  16244. (sday (calendar-absolute-from-gregorian base))
  16245. (cday (calendar-absolute-from-gregorian target))
  16246. n1 n2)
  16247. ;; If START is already past CURRENT, just return START.
  16248. (if (<= cday sday) sday
  16249. ;; Compute closest date before (N1) and closest date past
  16250. ;; (N2) CURRENT.
  16251. (pcase type
  16252. ("h"
  16253. (let ((missing-hours
  16254. (mod (+ (- (* 24 (- cday sday))
  16255. (nth 2 (org-parse-time-string start)))
  16256. org-extend-today-until)
  16257. value)))
  16258. (setf n1 (if (= missing-hours 0) cday
  16259. (- cday (1+ (/ missing-hours 24)))))
  16260. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16261. ((or "d" "w")
  16262. (let ((value (if (equal type "w") (* 7 value) value)))
  16263. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16264. (setf n2 (+ n1 value))))
  16265. ("m"
  16266. (let* ((add-months
  16267. (lambda (date n)
  16268. ;; Add N months to gregorian DATE, i.e.,
  16269. ;; a list (MONTH DAY YEAR). Return a valid
  16270. ;; gregorian date.
  16271. (let ((m (+ (nth 0 date) n)))
  16272. (list (mod m 12)
  16273. (nth 1 date)
  16274. (+ (/ m 12) (nth 2 date))))))
  16275. (months ; Complete months to TARGET.
  16276. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16277. (- (nth 0 target) (nth 0 base))
  16278. ;; If START's day is greater than
  16279. ;; TARGET's, remove incomplete month.
  16280. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16281. value)
  16282. value))
  16283. (before (funcall add-months base months)))
  16284. (setf n1 (calendar-absolute-from-gregorian before))
  16285. (setf n2
  16286. (calendar-absolute-from-gregorian
  16287. (funcall add-months before value)))))
  16288. (_
  16289. (let* ((d (nth 1 base))
  16290. (m (nth 0 base))
  16291. (y (nth 2 base))
  16292. (years ; Complete years to TARGET.
  16293. (* (/ (- (nth 2 target)
  16294. y
  16295. ;; If START's month and day are
  16296. ;; greater than TARGET's, remove
  16297. ;; incomplete year.
  16298. (if (or (> (nth 0 target) m)
  16299. (and (= (nth 0 target) m)
  16300. (> (nth 1 target) d)))
  16301. 0
  16302. 1))
  16303. value)
  16304. value))
  16305. (before (list m d (+ y years))))
  16306. (setf n1 (calendar-absolute-from-gregorian before))
  16307. (setf n2 (calendar-absolute-from-gregorian
  16308. (list m d (+ (nth 2 before) value)))))))
  16309. ;; Handle PREFER parameter, if any.
  16310. (cond
  16311. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16312. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16313. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16314. (defun org-date-to-gregorian (date)
  16315. "Turn any specification of DATE into a Gregorian date for the calendar."
  16316. (cond ((integerp date) (calendar-gregorian-from-absolute date))
  16317. ((and (listp date) (= (length date) 3)) date)
  16318. ((stringp date)
  16319. (setq date (org-parse-time-string date))
  16320. (list (nth 4 date) (nth 3 date) (nth 5 date)))
  16321. ((listp date)
  16322. (list (nth 4 date) (nth 3 date) (nth 5 date)))))
  16323. (defun org-parse-time-string (s &optional nodefault)
  16324. "Parse the standard Org-mode time string.
  16325. This should be a lot faster than the normal `parse-time-string'.
  16326. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16327. hour and minute fields will be nil if not given."
  16328. (cond ((string-match org-ts-regexp0 s)
  16329. (list 0
  16330. (when (or (match-beginning 8) (not nodefault))
  16331. (string-to-number (or (match-string 8 s) "0")))
  16332. (when (or (match-beginning 7) (not nodefault))
  16333. (string-to-number (or (match-string 7 s) "0")))
  16334. (string-to-number (match-string 4 s))
  16335. (string-to-number (match-string 3 s))
  16336. (string-to-number (match-string 2 s))
  16337. nil nil nil))
  16338. ((string-match "^<[^>]+>$" s)
  16339. (decode-time (seconds-to-time (org-matcher-time s))))
  16340. (t (error "Not a standard Org-mode time string: %s" s))))
  16341. (defun org-timestamp-up (&optional arg)
  16342. "Increase the date item at the cursor by one.
  16343. If the cursor is on the year, change the year. If it is on the month,
  16344. the day or the time, change that.
  16345. With prefix ARG, change by that many units."
  16346. (interactive "p")
  16347. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16348. (defun org-timestamp-down (&optional arg)
  16349. "Decrease the date item at the cursor by one.
  16350. If the cursor is on the year, change the year. If it is on the month,
  16351. the day or the time, change that.
  16352. With prefix ARG, change by that many units."
  16353. (interactive "p")
  16354. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16355. (defun org-timestamp-up-day (&optional arg)
  16356. "Increase the date in the time stamp by one day.
  16357. With prefix ARG, change that many days."
  16358. (interactive "p")
  16359. (if (and (not (org-at-timestamp-p t))
  16360. (org-at-heading-p))
  16361. (org-todo 'up)
  16362. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16363. (defun org-timestamp-down-day (&optional arg)
  16364. "Decrease the date in the time stamp by one day.
  16365. With prefix ARG, change that many days."
  16366. (interactive "p")
  16367. (if (and (not (org-at-timestamp-p t))
  16368. (org-at-heading-p))
  16369. (org-todo 'down)
  16370. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16371. (defun org-at-timestamp-p (&optional inactive-ok)
  16372. "Non-nil if point is inside a timestamp.
  16373. When optional argument INACTIVE-OK is non-nil, also consider
  16374. inactive timestamps.
  16375. When this function returns a non-nil value, match data is set
  16376. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16377. INACTIVE-OK."
  16378. (interactive)
  16379. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16380. (pos (point))
  16381. (ans (or (looking-at tsr)
  16382. (save-excursion
  16383. (skip-chars-backward "^[<\n\r\t")
  16384. (when (> (point) (point-min)) (backward-char 1))
  16385. (and (looking-at tsr)
  16386. (> (- (match-end 0) pos) -1))))))
  16387. (and ans
  16388. (boundp 'org-ts-what)
  16389. (setq org-ts-what
  16390. (cond
  16391. ((= pos (match-beginning 0)) 'bracket)
  16392. ;; Point is considered to be "on the bracket" whether
  16393. ;; it's really on it or right after it.
  16394. ((= pos (1- (match-end 0))) 'bracket)
  16395. ((= pos (match-end 0)) 'after)
  16396. ((org-pos-in-match-range pos 2) 'year)
  16397. ((org-pos-in-match-range pos 3) 'month)
  16398. ((org-pos-in-match-range pos 7) 'hour)
  16399. ((org-pos-in-match-range pos 8) 'minute)
  16400. ((or (org-pos-in-match-range pos 4)
  16401. (org-pos-in-match-range pos 5)) 'day)
  16402. ((and (> pos (or (match-end 8) (match-end 5)))
  16403. (< pos (match-end 0)))
  16404. (- pos (or (match-end 8) (match-end 5))))
  16405. (t 'day))))
  16406. ans))
  16407. (defun org-toggle-timestamp-type ()
  16408. "Toggle the type (<active> or [inactive]) of a time stamp."
  16409. (interactive)
  16410. (when (org-at-timestamp-p t)
  16411. (let ((beg (match-beginning 0)) (end (match-end 0))
  16412. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16413. (save-excursion
  16414. (goto-char beg)
  16415. (while (re-search-forward "[][<>]" end t)
  16416. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16417. t t)))
  16418. (message "Timestamp is now %sactive"
  16419. (if (equal (char-after beg) ?<) "" "in")))))
  16420. (defun org-at-clock-log-p nil
  16421. "Is the cursor on the clock log line?"
  16422. (save-excursion
  16423. (move-beginning-of-line 1)
  16424. (looking-at org-clock-line-re)))
  16425. (defvar org-clock-history) ; defined in org-clock.el
  16426. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16427. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16428. "Change the date in the time stamp at point.
  16429. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16430. `year', `minute', `second'. If WHAT is not given, the cursor position
  16431. in the timestamp determines what will be changed.
  16432. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16433. (let ((origin (point)) origin-cat
  16434. with-hm inactive
  16435. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16436. org-ts-what
  16437. extra rem
  16438. ts time time0 fixnext clrgx)
  16439. (unless (org-at-timestamp-p t)
  16440. (user-error "Not at a timestamp"))
  16441. (if (and (not what) (eq org-ts-what 'bracket))
  16442. (org-toggle-timestamp-type)
  16443. ;; Point isn't on brackets. Remember the part of the time-stamp
  16444. ;; the point was in. Indeed, size of time-stamps may change,
  16445. ;; but point must be kept in the same category nonetheless.
  16446. (setq origin-cat org-ts-what)
  16447. (when (and (not what) (not (eq org-ts-what 'day))
  16448. org-display-custom-times
  16449. (get-text-property (point) 'display)
  16450. (not (get-text-property (1- (point)) 'display)))
  16451. (setq org-ts-what 'day))
  16452. (setq org-ts-what (or what org-ts-what)
  16453. inactive (= (char-after (match-beginning 0)) ?\[)
  16454. ts (match-string 0))
  16455. (replace-match "")
  16456. (when (string-match
  16457. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16458. ts)
  16459. (setq extra (match-string 1 ts))
  16460. (when suppress-tmp-delay
  16461. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16462. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16463. (setq with-hm t))
  16464. (setq time0 (org-parse-time-string ts))
  16465. (when (and updown
  16466. (eq org-ts-what 'minute)
  16467. (not current-prefix-arg))
  16468. ;; This looks like s-up and s-down. Change by one rounding step.
  16469. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16470. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16471. (setcar (cdr time0) (+ (nth 1 time0)
  16472. (if (> n 0) (- rem) (- dm rem))))))
  16473. (setq time
  16474. (encode-time (or (car time0) 0)
  16475. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16476. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16477. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16478. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16479. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16480. (nthcdr 6 time0)))
  16481. (when (and (member org-ts-what '(hour minute))
  16482. extra
  16483. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16484. (setq extra (org-modify-ts-extra
  16485. extra
  16486. (if (eq org-ts-what 'hour) 2 5)
  16487. n dm)))
  16488. (when (integerp org-ts-what)
  16489. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16490. (when (eq what 'calendar)
  16491. (let ((cal-date (org-get-date-from-calendar)))
  16492. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16493. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16494. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16495. (setcar time0 (or (car time0) 0))
  16496. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16497. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16498. (setq time (apply 'encode-time time0))))
  16499. ;; Insert the new time-stamp, and ensure point stays in the same
  16500. ;; category as before (i.e. not after the last position in that
  16501. ;; category).
  16502. (let ((pos (point)))
  16503. ;; Stay before inserted string. `save-excursion' is of no use.
  16504. (setq org-last-changed-timestamp
  16505. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16506. (goto-char pos))
  16507. (save-match-data
  16508. (looking-at org-ts-regexp3)
  16509. (goto-char (cond
  16510. ;; `day' category ends before `hour' if any, or at
  16511. ;; the end of the day name.
  16512. ((eq origin-cat 'day)
  16513. (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16514. ((eq origin-cat 'hour) (min (match-end 7) origin))
  16515. ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
  16516. ((integerp origin-cat) (min (1- (match-end 0)) origin))
  16517. ;; `year' and `month' have both fixed size: point
  16518. ;; couldn't have moved into another part.
  16519. (t origin))))
  16520. ;; Update clock if on a CLOCK line.
  16521. (org-clock-update-time-maybe)
  16522. ;; Maybe adjust the closest clock in `org-clock-history'
  16523. (when org-clock-adjust-closest
  16524. (if (not (and (org-at-clock-log-p)
  16525. (< 1 (length (delq nil (mapcar 'marker-position
  16526. org-clock-history))))))
  16527. (message "No clock to adjust")
  16528. (cond ((save-excursion ; fix previous clock?
  16529. (re-search-backward org-ts-regexp0 nil t)
  16530. (org-looking-back (concat org-clock-string " \\[")
  16531. (line-beginning-position)))
  16532. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16533. ((save-excursion ; fix next clock?
  16534. (re-search-backward org-ts-regexp0 nil t)
  16535. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16536. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16537. (save-window-excursion
  16538. ;; Find closest clock to point, adjust the previous/next one in history
  16539. (let* ((p (save-excursion (org-back-to-heading t)))
  16540. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16541. (clfixnth
  16542. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16543. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16544. (if (not clfixpos)
  16545. (message "No clock to adjust")
  16546. (save-excursion
  16547. (org-goto-marker-or-bmk clfixpos)
  16548. (org-show-subtree)
  16549. (when (re-search-forward clrgx nil t)
  16550. (goto-char (match-beginning 1))
  16551. (let (org-clock-adjust-closest)
  16552. (org-timestamp-change n org-ts-what updown))
  16553. (message "Clock adjusted in %s for heading: %s"
  16554. (file-name-nondirectory (buffer-file-name))
  16555. (org-get-heading t t)))))))))
  16556. ;; Try to recenter the calendar window, if any.
  16557. (when (and org-calendar-follow-timestamp-change
  16558. (get-buffer-window "*Calendar*" t)
  16559. (memq org-ts-what '(day month year)))
  16560. (org-recenter-calendar (time-to-days time))))))
  16561. (defun org-modify-ts-extra (s pos n dm)
  16562. "Change the different parts of the lead-time and repeat fields in timestamp."
  16563. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16564. ng h m new rem)
  16565. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16566. (cond
  16567. ((or (org-pos-in-match-range pos 2)
  16568. (org-pos-in-match-range pos 3))
  16569. (setq m (string-to-number (match-string 3 s))
  16570. h (string-to-number (match-string 2 s)))
  16571. (if (org-pos-in-match-range pos 2)
  16572. (setq h (+ h n))
  16573. (setq n (* dm (org-no-warnings (signum n))))
  16574. (unless (= 0 (setq rem (% m dm)))
  16575. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16576. (setq m (+ m n)))
  16577. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16578. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16579. (setq h (mod h 24))
  16580. (setq ng 1 new (format "-%02d:%02d" h m)))
  16581. ((org-pos-in-match-range pos 6)
  16582. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16583. ((org-pos-in-match-range pos 5)
  16584. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16585. ((org-pos-in-match-range pos 9)
  16586. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16587. ((org-pos-in-match-range pos 8)
  16588. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16589. (when ng
  16590. (setq s (concat
  16591. (substring s 0 (match-beginning ng))
  16592. new
  16593. (substring s (match-end ng))))))
  16594. s))
  16595. (defun org-recenter-calendar (date)
  16596. "If the calendar is visible, recenter it to DATE."
  16597. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16598. (when cwin
  16599. (let ((calendar-move-hook nil))
  16600. (with-selected-window cwin
  16601. (calendar-goto-date (if (listp date) date
  16602. (calendar-gregorian-from-absolute date))))))))
  16603. (defun org-goto-calendar (&optional arg)
  16604. "Go to the Emacs calendar at the current date.
  16605. If there is a time stamp in the current line, go to that date.
  16606. A prefix ARG can be used to force the current date."
  16607. (interactive "P")
  16608. (let ((tsr org-ts-regexp) diff
  16609. (calendar-move-hook nil)
  16610. (calendar-view-holidays-initially-flag nil)
  16611. (calendar-view-diary-initially-flag nil))
  16612. (when (or (org-at-timestamp-p)
  16613. (save-excursion
  16614. (beginning-of-line 1)
  16615. (looking-at (concat ".*" tsr))))
  16616. (let ((d1 (time-to-days (current-time)))
  16617. (d2 (time-to-days
  16618. (org-time-string-to-time (match-string 1)))))
  16619. (setq diff (- d2 d1))))
  16620. (calendar)
  16621. (calendar-goto-today)
  16622. (when (and diff (not arg)) (calendar-forward-day diff))))
  16623. (defun org-get-date-from-calendar ()
  16624. "Return a list (month day year) of date at point in calendar."
  16625. (with-current-buffer "*Calendar*"
  16626. (save-match-data
  16627. (calendar-cursor-to-date))))
  16628. (defun org-date-from-calendar ()
  16629. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16630. If there is already a time stamp at the cursor position, update it."
  16631. (interactive)
  16632. (if (org-at-timestamp-p t)
  16633. (org-timestamp-change 0 'calendar)
  16634. (let ((cal-date (org-get-date-from-calendar)))
  16635. (org-insert-time-stamp
  16636. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16637. (defcustom org-effort-durations
  16638. `(("min" . 1)
  16639. ("h" . 60)
  16640. ("d" . ,(* 60 8))
  16641. ("w" . ,(* 60 8 5))
  16642. ("m" . ,(* 60 8 5 4))
  16643. ("y" . ,(* 60 8 5 40)))
  16644. "Conversion factor to minutes for an effort modifier.
  16645. Each entry has the form (MODIFIER . MINUTES).
  16646. In an effort string, a number followed by MODIFIER is multiplied
  16647. by the specified number of MINUTES to obtain an effort in
  16648. minutes.
  16649. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16650. effort string \"2hours\" is equivalent to 120 minutes."
  16651. :group 'org-agenda
  16652. :version "25.1"
  16653. :package-version '(Org . "8.3")
  16654. :type '(alist :key-type (string :tag "Modifier")
  16655. :value-type (number :tag "Minutes")))
  16656. (defun org-minutes-to-clocksum-string (m)
  16657. "Format number of minutes as a clocksum string.
  16658. The format is determined by `org-time-clocksum-format',
  16659. `org-time-clocksum-use-fractional' and
  16660. `org-time-clocksum-fractional-format' and
  16661. `org-time-clocksum-use-effort-durations'."
  16662. (let ((clocksum "")
  16663. (m (round m)) ; Don't allow fractions of minutes
  16664. h d w mo y fmt n)
  16665. (setq h (if org-time-clocksum-use-effort-durations
  16666. (cdr (assoc "h" org-effort-durations)) 60)
  16667. d (if org-time-clocksum-use-effort-durations
  16668. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16669. w (if org-time-clocksum-use-effort-durations
  16670. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16671. mo (if org-time-clocksum-use-effort-durations
  16672. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16673. y (if org-time-clocksum-use-effort-durations
  16674. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16675. ;; fractional format
  16676. (if org-time-clocksum-use-fractional
  16677. (cond
  16678. ;; single format string
  16679. ((stringp org-time-clocksum-fractional-format)
  16680. (format org-time-clocksum-fractional-format (/ m (float h))))
  16681. ;; choice of fractional formats for different time units
  16682. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16683. (> (/ (truncate m) (* y d h)) 0))
  16684. (format fmt (/ m (* y d (float h)))))
  16685. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16686. (> (/ (truncate m) (* mo d h)) 0))
  16687. (format fmt (/ m (* mo d (float h)))))
  16688. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16689. (> (/ (truncate m) (* w d h)) 0))
  16690. (format fmt (/ m (* w d (float h)))))
  16691. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16692. (> (/ (truncate m) (* d h)) 0))
  16693. (format fmt (/ m (* d (float h)))))
  16694. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16695. (> (/ (truncate m) h) 0))
  16696. (format fmt (/ m (float h))))
  16697. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16698. (format fmt m))
  16699. ;; fall back to smallest time unit with a format
  16700. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16701. (format fmt (/ m (float h))))
  16702. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16703. (format fmt (/ m (* d (float h)))))
  16704. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16705. (format fmt (/ m (* w d (float h)))))
  16706. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16707. (format fmt (/ m (* mo d (float h)))))
  16708. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16709. (format fmt (/ m (* y d (float h))))))
  16710. ;; standard (non-fractional) format, with single format string
  16711. (if (stringp org-time-clocksum-format)
  16712. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16713. ;; separate formats components
  16714. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16715. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16716. (plist-get org-time-clocksum-format :require-years))
  16717. (setq clocksum (concat clocksum (format fmt n))
  16718. m (- m (* n y d h))))
  16719. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16720. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16721. (plist-get org-time-clocksum-format :require-months))
  16722. (setq clocksum (concat clocksum (format fmt n))
  16723. m (- m (* n mo d h))))
  16724. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16725. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16726. (plist-get org-time-clocksum-format :require-weeks))
  16727. (setq clocksum (concat clocksum (format fmt n))
  16728. m (- m (* n w d h))))
  16729. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16730. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16731. (plist-get org-time-clocksum-format :require-days))
  16732. (setq clocksum (concat clocksum (format fmt n))
  16733. m (- m (* n d h))))
  16734. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16735. (or (> (setq n (/ (truncate m) h)) 0)
  16736. (plist-get org-time-clocksum-format :require-hours))
  16737. (setq clocksum (concat clocksum (format fmt n))
  16738. m (- m (* n h))))
  16739. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16740. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16741. (setq clocksum (concat clocksum (format fmt m))))
  16742. ;; return formatted time duration
  16743. clocksum))))
  16744. (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
  16745. (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
  16746. "Org mode version 8.0")
  16747. (defun org-hours-to-clocksum-string (n)
  16748. (org-minutes-to-clocksum-string (* n 60)))
  16749. (defun org-hh:mm-string-to-minutes (s)
  16750. "Convert a string H:MM to a number of minutes.
  16751. If the string is just a number, interpret it as minutes.
  16752. In fact, the first hh:mm or number in the string will be taken,
  16753. there can be extra stuff in the string.
  16754. If no number is found, the return value is 0."
  16755. (cond
  16756. ((integerp s) s)
  16757. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16758. (+ (* (string-to-number (match-string 1 s)) 60)
  16759. (string-to-number (match-string 2 s))))
  16760. ((string-match "\\([0-9]+\\)" s)
  16761. (string-to-number (match-string 1 s)))
  16762. (t 0)))
  16763. (defcustom org-image-actual-width t
  16764. "Should we use the actual width of images when inlining them?
  16765. When set to t, always use the image width.
  16766. When set to a number, use imagemagick (when available) to set
  16767. the image's width to this value.
  16768. When set to a number in a list, try to get the width from any
  16769. #+ATTR.* keyword if it matches a width specification like
  16770. #+ATTR_HTML: :width 300px
  16771. and fall back on that number if none is found.
  16772. When set to nil, try to get the width from an #+ATTR.* keyword
  16773. and fall back on the original width if none is found.
  16774. This requires Emacs >= 24.1, build with imagemagick support."
  16775. :group 'org-appearance
  16776. :version "24.4"
  16777. :package-version '(Org . "8.0")
  16778. :type '(choice
  16779. (const :tag "Use the image width" t)
  16780. (integer :tag "Use a number of pixels")
  16781. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16782. (const :tag "Use #+ATTR* or don't resize" nil)))
  16783. (defcustom org-agenda-inhibit-startup nil
  16784. "Inhibit startup when preparing agenda buffers.
  16785. When this variable is t, the initialization of the Org agenda
  16786. buffers is inhibited: e.g. the visibility state is not set, the
  16787. tables are not re-aligned, etc."
  16788. :type 'boolean
  16789. :version "24.3"
  16790. :group 'org-agenda)
  16791. (define-obsolete-variable-alias
  16792. 'org-agenda-ignore-drawer-properties
  16793. 'org-agenda-ignore-properties "25.1")
  16794. (defcustom org-agenda-ignore-properties nil
  16795. "Avoid updating text properties when building the agenda.
  16796. Properties are used to prepare buffers for effort estimates,
  16797. appointments, statistics and subtree-local categories.
  16798. If you don't use these in the agenda, you can add them to this
  16799. list and agenda building will be a bit faster.
  16800. The value is a list, with zero or more of the symbols `effort', `appt',
  16801. `stats' or `category'."
  16802. :type '(set :greedy t
  16803. (const effort)
  16804. (const appt)
  16805. (const stats)
  16806. (const category))
  16807. :version "25.1"
  16808. :package-version '(Org . "8.3")
  16809. :group 'org-agenda)
  16810. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16811. "Convert a duration string S to minutes.
  16812. A bare number is interpreted as minutes, modifiers can be set by
  16813. customizing `org-effort-durations' (which see).
  16814. Entries containing a colon are interpreted as H:MM by
  16815. `org-hh:mm-string-to-minutes'."
  16816. (let ((result 0)
  16817. (re (concat "\\([0-9.]+\\) *\\("
  16818. (regexp-opt (mapcar 'car org-effort-durations))
  16819. "\\)")))
  16820. (while (string-match re s)
  16821. (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16822. (string-to-number (match-string 1 s))))
  16823. (setq s (replace-match "" nil t s)))
  16824. (setq result (floor result))
  16825. (incf result (org-hh:mm-string-to-minutes s))
  16826. (if output-to-string (number-to-string result) result)))
  16827. ;;;; Files
  16828. (defun org-save-all-org-buffers ()
  16829. "Save all Org-mode buffers without user confirmation."
  16830. (interactive)
  16831. (message "Saving all Org-mode buffers...")
  16832. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16833. (when (featurep 'org-id) (org-id-locations-save))
  16834. (message "Saving all Org-mode buffers... done"))
  16835. (defun org-revert-all-org-buffers ()
  16836. "Revert all Org-mode buffers.
  16837. Prompt for confirmation when there are unsaved changes.
  16838. Be sure you know what you are doing before letting this function
  16839. overwrite your changes.
  16840. This function is useful in a setup where one tracks org files
  16841. with a version control system, to revert on one machine after pulling
  16842. changes from another. I believe the procedure must be like this:
  16843. 1. M-x org-save-all-org-buffers
  16844. 2. Pull changes from the other machine, resolve conflicts
  16845. 3. M-x org-revert-all-org-buffers"
  16846. (interactive)
  16847. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16848. (user-error "Abort"))
  16849. (save-excursion
  16850. (save-window-excursion
  16851. (mapc
  16852. (lambda (b)
  16853. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16854. (with-current-buffer b buffer-file-name))
  16855. (org-pop-to-buffer-same-window b)
  16856. (revert-buffer t 'no-confirm)))
  16857. (buffer-list))
  16858. (when (and (featurep 'org-id) org-id-track-globally)
  16859. (org-id-locations-load)))))
  16860. ;;;; Agenda files
  16861. ;;;###autoload
  16862. (defun org-switchb (&optional arg)
  16863. "Switch between Org buffers.
  16864. With one prefix argument, restrict available buffers to files.
  16865. With two prefix arguments, restrict available buffers to agenda files.
  16866. Defaults to `iswitchb' for buffer name completion.
  16867. Set `org-completion-use-ido' to make it use ido instead."
  16868. (interactive "P")
  16869. (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
  16870. ((equal arg '(16)) (org-buffer-list 'agenda))
  16871. (t (org-buffer-list))))
  16872. (org-completion-use-iswitchb org-completion-use-iswitchb)
  16873. (org-completion-use-ido org-completion-use-ido))
  16874. (unless (or org-completion-use-ido org-completion-use-iswitchb)
  16875. (setq org-completion-use-iswitchb t))
  16876. (org-pop-to-buffer-same-window
  16877. (org-icompleting-read "Org buffer: "
  16878. (mapcar 'list (mapcar 'buffer-name blist))
  16879. nil t))))
  16880. ;;; Define some older names previously used for this functionality
  16881. ;;;###autoload
  16882. (defalias 'org-ido-switchb 'org-switchb)
  16883. ;;;###autoload
  16884. (defalias 'org-iswitchb 'org-switchb)
  16885. (defun org-buffer-list (&optional predicate exclude-tmp)
  16886. "Return a list of Org buffers.
  16887. PREDICATE can be `export', `files' or `agenda'.
  16888. export restrict the list to Export buffers.
  16889. files restrict the list to buffers visiting Org files.
  16890. agenda restrict the list to buffers visiting agenda files.
  16891. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16892. (let* ((bfn nil)
  16893. (agenda-files (and (eq predicate 'agenda)
  16894. (mapcar 'file-truename (org-agenda-files t))))
  16895. (filter
  16896. (cond
  16897. ((eq predicate 'files)
  16898. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16899. ((eq predicate 'export)
  16900. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16901. ((eq predicate 'agenda)
  16902. (lambda (b)
  16903. (with-current-buffer b
  16904. (and (derived-mode-p 'org-mode)
  16905. (setq bfn (buffer-file-name b))
  16906. (member (file-truename bfn) agenda-files)))))
  16907. (t (lambda (b) (with-current-buffer b
  16908. (or (derived-mode-p 'org-mode)
  16909. (string-match "\\*Org .*Export"
  16910. (buffer-name b)))))))))
  16911. (delq nil
  16912. (mapcar
  16913. (lambda(b)
  16914. (if (and (funcall filter b)
  16915. (or (not exclude-tmp)
  16916. (not (string-match "tmp" (buffer-name b)))))
  16917. b
  16918. nil))
  16919. (buffer-list)))))
  16920. (defun org-agenda-files (&optional unrestricted archives)
  16921. "Get the list of agenda files.
  16922. Optional UNRESTRICTED means return the full list even if a restriction
  16923. is currently in place.
  16924. When ARCHIVES is t, include all archive files that are really being
  16925. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16926. `org-agenda-archives-mode' is t."
  16927. (let ((files
  16928. (cond
  16929. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16930. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16931. ((listp org-agenda-files) org-agenda-files)
  16932. (t (error "Invalid value of `org-agenda-files'")))))
  16933. (setq files (apply 'append
  16934. (mapcar (lambda (f)
  16935. (if (file-directory-p f)
  16936. (directory-files
  16937. f t org-agenda-file-regexp)
  16938. (list f)))
  16939. files)))
  16940. (when org-agenda-skip-unavailable-files
  16941. (setq files (delq nil
  16942. (mapcar (function
  16943. (lambda (file)
  16944. (and (file-readable-p file) file)))
  16945. files))))
  16946. (when (or (eq archives t)
  16947. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16948. (setq files (org-add-archive-files files)))
  16949. files))
  16950. (defun org-agenda-file-p (&optional file)
  16951. "Return non-nil, if FILE is an agenda file.
  16952. If FILE is omitted, use the file associated with the current
  16953. buffer."
  16954. (let ((fname (or file (buffer-file-name))))
  16955. (and fname
  16956. (member (file-truename fname)
  16957. (mapcar #'file-truename (org-agenda-files t))))))
  16958. (defun org-edit-agenda-file-list ()
  16959. "Edit the list of agenda files.
  16960. Depending on setup, this either uses customize to edit the variable
  16961. `org-agenda-files', or it visits the file that is holding the list. In the
  16962. latter case, the buffer is set up in a way that saving it automatically kills
  16963. the buffer and restores the previous window configuration."
  16964. (interactive)
  16965. (if (stringp org-agenda-files)
  16966. (let ((cw (current-window-configuration)))
  16967. (find-file org-agenda-files)
  16968. (setq-local org-window-configuration cw)
  16969. (org-add-hook 'after-save-hook
  16970. (lambda ()
  16971. (set-window-configuration
  16972. (prog1 org-window-configuration
  16973. (kill-buffer (current-buffer))))
  16974. (org-install-agenda-files-menu)
  16975. (message "New agenda file list installed"))
  16976. nil 'local)
  16977. (message "%s" (substitute-command-keys
  16978. "Edit list and finish with \\[save-buffer]")))
  16979. (customize-variable 'org-agenda-files)))
  16980. (defun org-store-new-agenda-file-list (list)
  16981. "Set new value for the agenda file list and save it correctly."
  16982. (if (stringp org-agenda-files)
  16983. (let ((fe (org-read-agenda-file-list t)) b u)
  16984. (while (setq b (find-buffer-visiting org-agenda-files))
  16985. (kill-buffer b))
  16986. (with-temp-file org-agenda-files
  16987. (insert
  16988. (mapconcat
  16989. (lambda (f) ;; Keep un-expanded entries.
  16990. (if (setq u (assoc f fe))
  16991. (cdr u)
  16992. f))
  16993. list "\n")
  16994. "\n")))
  16995. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16996. (org-insert-mode-line-in-empty-file nil))
  16997. (setq org-agenda-files list)
  16998. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16999. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17000. "Read the list of agenda files from a file.
  17001. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17002. filenames, used by `org-store-new-agenda-file-list' to write back
  17003. un-expanded file names."
  17004. (when (file-directory-p org-agenda-files)
  17005. (error "`org-agenda-files' cannot be a single directory"))
  17006. (when (stringp org-agenda-files)
  17007. (with-temp-buffer
  17008. (insert-file-contents org-agenda-files)
  17009. (mapcar
  17010. (lambda (f)
  17011. (let ((e (expand-file-name (substitute-in-file-name f)
  17012. org-directory)))
  17013. (if pair-with-expansion
  17014. (cons e f)
  17015. e)))
  17016. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17017. ;;;###autoload
  17018. (defun org-cycle-agenda-files ()
  17019. "Cycle through the files in `org-agenda-files'.
  17020. If the current buffer visits an agenda file, find the next one in the list.
  17021. If the current buffer does not, find the first agenda file."
  17022. (interactive)
  17023. (let* ((fs (or (org-agenda-files t)
  17024. (user-error "No agenda files")))
  17025. (files (copy-sequence fs))
  17026. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17027. file)
  17028. (when tcf
  17029. (while (and (setq file (pop files))
  17030. (not (equal (file-truename file) tcf)))))
  17031. (find-file (car (or files fs)))
  17032. (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
  17033. (defun org-agenda-file-to-front (&optional to-end)
  17034. "Move/add the current file to the top of the agenda file list.
  17035. If the file is not present in the list, it is added to the front. If it is
  17036. present, it is moved there. With optional argument TO-END, add/move to the
  17037. end of the list."
  17038. (interactive "P")
  17039. (let ((org-agenda-skip-unavailable-files nil)
  17040. (file-alist (mapcar (lambda (x)
  17041. (cons (file-truename x) x))
  17042. (org-agenda-files t)))
  17043. (ctf (file-truename
  17044. (or buffer-file-name
  17045. (user-error "Please save the current buffer to a file"))))
  17046. x had)
  17047. (setq x (assoc ctf file-alist) had x)
  17048. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17049. (if to-end
  17050. (setq file-alist (append (delq x file-alist) (list x)))
  17051. (setq file-alist (cons x (delq x file-alist))))
  17052. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17053. (org-install-agenda-files-menu)
  17054. (message "File %s to %s of agenda file list"
  17055. (if had "moved" "added") (if to-end "end" "front"))))
  17056. (defun org-remove-file (&optional file)
  17057. "Remove current file from the list of files in variable `org-agenda-files'.
  17058. These are the files which are being checked for agenda entries.
  17059. Optional argument FILE means use this file instead of the current."
  17060. (interactive)
  17061. (let* ((org-agenda-skip-unavailable-files nil)
  17062. (file (or file buffer-file-name
  17063. (user-error "Current buffer does not visit a file")))
  17064. (true-file (file-truename file))
  17065. (afile (abbreviate-file-name file))
  17066. (files (delq nil (mapcar
  17067. (lambda (x)
  17068. (unless (equal true-file
  17069. (file-truename x))
  17070. x))
  17071. (org-agenda-files t)))))
  17072. (if (not (= (length files) (length (org-agenda-files t))))
  17073. (progn
  17074. (org-store-new-agenda-file-list files)
  17075. (org-install-agenda-files-menu)
  17076. (message "Removed from Org Agenda list: %s" afile))
  17077. (message "File was not in list: %s (not removed)" afile))))
  17078. (defun org-file-menu-entry (file)
  17079. (vector file (list 'find-file file) t))
  17080. (defun org-check-agenda-file (file)
  17081. "Make sure FILE exists. If not, ask user what to do."
  17082. (unless (file-exists-p file)
  17083. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17084. (abbreviate-file-name file))
  17085. (let ((r (downcase (read-char-exclusive))))
  17086. (cond
  17087. ((equal r ?r)
  17088. (org-remove-file file)
  17089. (throw 'nextfile t))
  17090. (t (user-error "Abort"))))))
  17091. (defun org-get-agenda-file-buffer (file)
  17092. "Get an agenda buffer visiting FILE.
  17093. If the buffer needs to be created, add it to the list of buffers
  17094. which might be released later."
  17095. (let ((buf (org-find-base-buffer-visiting file)))
  17096. (if buf
  17097. buf ; just return it
  17098. ;; Make a new buffer and remember it
  17099. (setq buf (find-file-noselect file))
  17100. (when buf (push buf org-agenda-new-buffers))
  17101. buf)))
  17102. (defun org-release-buffers (blist)
  17103. "Release all buffers in list, asking the user for confirmation when needed.
  17104. When a buffer is unmodified, it is just killed. When modified, it is saved
  17105. \(if the user agrees) and then killed."
  17106. (let (file)
  17107. (dolist (buf blist)
  17108. (setq file (buffer-file-name buf))
  17109. (when (and (buffer-modified-p buf)
  17110. file
  17111. (y-or-n-p (format "Save file %s? " file)))
  17112. (with-current-buffer buf (save-buffer)))
  17113. (kill-buffer buf))))
  17114. (defun org-agenda-prepare-buffers (files)
  17115. "Create buffers for all agenda files, protect archived trees and comments."
  17116. (interactive)
  17117. (let ((pa '(:org-archived t))
  17118. (pc '(:org-comment t))
  17119. (pall '(:org-archived t :org-comment t))
  17120. (inhibit-read-only t)
  17121. (org-inhibit-startup org-agenda-inhibit-startup)
  17122. (rea (concat ":" org-archive-tag ":"))
  17123. file re pos)
  17124. (setq org-tag-alist-for-agenda nil
  17125. org-tag-groups-alist-for-agenda nil)
  17126. (save-excursion
  17127. (save-restriction
  17128. (dolist (file files)
  17129. (catch 'nextfile
  17130. (if (bufferp file)
  17131. (set-buffer file)
  17132. (org-check-agenda-file file)
  17133. (set-buffer (org-get-agenda-file-buffer file)))
  17134. (widen)
  17135. (org-set-regexps-and-options 'tags-only)
  17136. (setq pos (point))
  17137. (or (memq 'category org-agenda-ignore-properties)
  17138. (org-refresh-category-properties))
  17139. (or (memq 'stats org-agenda-ignore-properties)
  17140. (org-refresh-stats-properties))
  17141. (or (memq 'effort org-agenda-ignore-properties)
  17142. (org-refresh-effort-properties))
  17143. (or (memq 'appt org-agenda-ignore-properties)
  17144. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17145. (setq org-todo-keywords-for-agenda
  17146. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17147. (setq org-done-keywords-for-agenda
  17148. (append org-done-keywords-for-agenda org-done-keywords))
  17149. (setq org-todo-keyword-alist-for-agenda
  17150. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17151. (setq org-tag-alist-for-agenda
  17152. (org-uniquify
  17153. (append org-tag-alist-for-agenda
  17154. org-tag-alist
  17155. org-tag-persistent-alist)))
  17156. (when org-group-tags
  17157. (setq org-tag-groups-alist-for-agenda
  17158. (org-uniquify-alist
  17159. (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
  17160. (org-with-silent-modifications
  17161. (save-excursion
  17162. (remove-text-properties (point-min) (point-max) pall)
  17163. (when org-agenda-skip-archived-trees
  17164. (goto-char (point-min))
  17165. (while (re-search-forward rea nil t)
  17166. (when (org-at-heading-p t)
  17167. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17168. (goto-char (point-min))
  17169. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17170. (while (re-search-forward re nil t)
  17171. (when (save-match-data (org-in-commented-heading-p t))
  17172. (add-text-properties
  17173. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17174. (goto-char pos)))))
  17175. (setq org-todo-keywords-for-agenda
  17176. (org-uniquify org-todo-keywords-for-agenda))
  17177. (setq org-todo-keyword-alist-for-agenda
  17178. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17179. ;;;; CDLaTeX minor mode
  17180. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17181. "Keymap for the minor `org-cdlatex-mode'.")
  17182. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17183. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17184. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17185. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17186. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17187. (defvar org-cdlatex-texmathp-advice-is-done nil
  17188. "Flag remembering if we have applied the advice to texmathp already.")
  17189. (define-minor-mode org-cdlatex-mode
  17190. "Toggle the minor `org-cdlatex-mode'.
  17191. This mode supports entering LaTeX environment and math in LaTeX fragments
  17192. in Org-mode.
  17193. \\{org-cdlatex-mode-map}"
  17194. nil " OCDL" nil
  17195. (when org-cdlatex-mode
  17196. (require 'cdlatex)
  17197. (run-hooks 'cdlatex-mode-hook)
  17198. (cdlatex-compute-tables))
  17199. (unless org-cdlatex-texmathp-advice-is-done
  17200. (setq org-cdlatex-texmathp-advice-is-done t)
  17201. (defadvice texmathp (around org-math-always-on activate)
  17202. "Always return t in org-mode buffers.
  17203. This is because we want to insert math symbols without dollars even outside
  17204. the LaTeX math segments. If Orgmode thinks that point is actually inside
  17205. an embedded LaTeX fragment, let texmathp do its job.
  17206. \\[org-cdlatex-mode-map]"
  17207. (interactive)
  17208. (let (p)
  17209. (cond
  17210. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17211. ((eq this-command 'cdlatex-math-symbol)
  17212. (setq ad-return-value t
  17213. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17214. (t
  17215. (let ((p (org-inside-LaTeX-fragment-p)))
  17216. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17217. (setq ad-return-value t
  17218. texmathp-why '("Org-mode embedded math" . 0))
  17219. (when p ad-do-it)))))))))
  17220. (defun turn-on-org-cdlatex ()
  17221. "Unconditionally turn on `org-cdlatex-mode'."
  17222. (org-cdlatex-mode 1))
  17223. (defun org-try-cdlatex-tab ()
  17224. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17225. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17226. - inside a LaTeX fragment, or
  17227. - after the first word in a line, where an abbreviation expansion could
  17228. insert a LaTeX environment."
  17229. (when org-cdlatex-mode
  17230. (cond
  17231. ;; Before any word on the line: No expansion possible.
  17232. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17233. ;; Just after first word on the line: Expand it. Make sure it
  17234. ;; cannot happen on headlines, though.
  17235. ((save-excursion
  17236. (skip-chars-backward "a-zA-Z0-9*")
  17237. (skip-chars-backward " \t")
  17238. (and (bolp) (not (org-at-heading-p))))
  17239. (cdlatex-tab) t)
  17240. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17241. (defun org-cdlatex-underscore-caret (&optional arg)
  17242. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17243. Revert to the normal definition outside of these fragments."
  17244. (interactive "P")
  17245. (if (org-inside-LaTeX-fragment-p)
  17246. (call-interactively 'cdlatex-sub-superscript)
  17247. (let (org-cdlatex-mode)
  17248. (call-interactively (key-binding (vector last-input-event))))))
  17249. (defun org-cdlatex-math-modify (&optional arg)
  17250. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17251. Revert to the normal definition outside of these fragments."
  17252. (interactive "P")
  17253. (if (org-inside-LaTeX-fragment-p)
  17254. (call-interactively 'cdlatex-math-modify)
  17255. (let (org-cdlatex-mode)
  17256. (call-interactively (key-binding (vector last-input-event))))))
  17257. (defun org-cdlatex-environment-indent (&optional environment item)
  17258. "Execute `cdlatex-environment' and indent the inserted environment.
  17259. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17260. The inserted environment is indented to current indentation
  17261. unless point is at the beginning of the line, in which the
  17262. environment remains unintended."
  17263. (interactive)
  17264. ;; cdlatex-environment always return nil. Therefore, capture output
  17265. ;; first and determine if an environment was selected.
  17266. (let* ((beg (point-marker))
  17267. (end (copy-marker (point) t))
  17268. (inserted (progn
  17269. (ignore-errors (cdlatex-environment environment item))
  17270. (< beg end)))
  17271. ;; Figure out how many lines to move forward after the
  17272. ;; environment has been inserted.
  17273. (lines (when inserted
  17274. (save-excursion
  17275. (- (loop while (< beg (point))
  17276. with x = 0
  17277. do (forward-line -1)
  17278. (incf x)
  17279. finally return x)
  17280. (if (progn (goto-char beg)
  17281. (and (progn (skip-chars-forward " \t") (eolp))
  17282. (progn (skip-chars-backward " \t") (bolp))))
  17283. 1 0)))))
  17284. (env (org-trim (delete-and-extract-region beg end))))
  17285. (when inserted
  17286. ;; Get indentation of next line unless at column 0.
  17287. (let ((ind (if (bolp) 0
  17288. (save-excursion
  17289. (org-return-indent)
  17290. (prog1 (org-get-indentation)
  17291. (when (progn (skip-chars-forward " \t") (eolp))
  17292. (delete-region beg (point)))))))
  17293. (bol (progn (skip-chars-backward " \t") (bolp))))
  17294. ;; Insert a newline before environment unless at column zero
  17295. ;; to "escape" the current line. Insert a newline if
  17296. ;; something is one the same line as \end{ENVIRONMENT}.
  17297. (insert
  17298. (concat (unless bol "\n") env
  17299. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17300. (unless (zerop ind)
  17301. (save-excursion
  17302. (goto-char beg)
  17303. (while (< (point) end)
  17304. (unless (eolp) (org-indent-line-to ind))
  17305. (forward-line))))
  17306. (goto-char beg)
  17307. (forward-line lines)
  17308. (org-indent-line-to ind)))
  17309. (set-marker beg nil)
  17310. (set-marker end nil)))
  17311. ;;;; LaTeX fragments
  17312. (defun org-inside-LaTeX-fragment-p ()
  17313. "Test if point is inside a LaTeX fragment.
  17314. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17315. sequence appearing also before point.
  17316. Even though the matchers for math are configurable, this function assumes
  17317. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17318. delimiters are skipped when they have been removed by customization.
  17319. The return value is nil, or a cons cell with the delimiter and the
  17320. position of this delimiter.
  17321. This function does a reasonably good job, but can locally be fooled by
  17322. for example currency specifications. For example it will assume being in
  17323. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17324. fragments that are properly closed, but during editing, we have to live
  17325. with the uncertainty caused by missing closing delimiters. This function
  17326. looks only before point, not after."
  17327. (catch 'exit
  17328. (let ((pos (point))
  17329. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17330. (lim (progn
  17331. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17332. (point)))
  17333. dd-on str (start 0) m re)
  17334. (goto-char pos)
  17335. (when dodollar
  17336. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17337. re (nth 1 (assoc "$" org-latex-regexps)))
  17338. (while (string-match re str start)
  17339. (cond
  17340. ((= (match-end 0) (length str))
  17341. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17342. ((= (match-end 0) (- (length str) 5))
  17343. (throw 'exit nil))
  17344. (t (setq start (match-end 0))))))
  17345. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17346. (goto-char pos)
  17347. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17348. (and (match-beginning 2) (throw 'exit nil))
  17349. ;; count $$
  17350. (while (re-search-backward "\\$\\$" lim t)
  17351. (setq dd-on (not dd-on)))
  17352. (goto-char pos)
  17353. (when dd-on (cons "$$" m))))))
  17354. (defun org-inside-latex-macro-p ()
  17355. "Is point inside a LaTeX macro or its arguments?"
  17356. (save-match-data
  17357. (org-in-regexp
  17358. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17359. (defvar-local org-latex-fragment-image-overlays nil
  17360. "List of overlays carrying the images of latex fragments.")
  17361. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17362. "Remove all overlays with LaTeX fragment images in current buffer.
  17363. When optional arguments BEG and END are non-nil, remove all
  17364. overlays between them instead. Return t when some overlays were
  17365. removed, nil otherwise."
  17366. (let (removedp)
  17367. (setq org-latex-fragment-image-overlays
  17368. (let ((beg (or beg (point-min)))
  17369. (end (or end (point-max))))
  17370. (cl-remove-if
  17371. (lambda (o)
  17372. (cond ((not (overlay-buffer o)) (delete-overlay o) t)
  17373. ((and (>= (overlay-start o) beg)
  17374. (<= (overlay-end o) end))
  17375. (delete-overlay o)
  17376. (unless removedp (setq removedp t)))
  17377. (t nil)))
  17378. org-latex-fragment-image-overlays)))
  17379. removedp))
  17380. (define-obsolete-function-alias
  17381. 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
  17382. (defun org-toggle-latex-fragment (&optional arg)
  17383. "Preview the LaTeX fragment at point, or all locally or globally.
  17384. If the cursor is on a LaTeX fragment, create the image and overlay
  17385. it over the source code, if there is none. Remove it otherwise.
  17386. If there is no fragment at point, display all fragments in the
  17387. current section.
  17388. With prefix ARG, preview or clear image for all fragments in the
  17389. current subtree or in the whole buffer when used before the first
  17390. headline. With a double prefix ARG \\[universal-argument] \
  17391. \\[universal-argument] preview or clear images
  17392. for all fragments in the buffer."
  17393. (interactive "P")
  17394. (unless (buffer-file-name (buffer-base-buffer))
  17395. (user-error "Can't preview LaTeX fragment in a non-file buffer"))
  17396. (when (display-graphic-p)
  17397. (catch 'exit
  17398. (save-excursion
  17399. (let ((window-start (window-start)) msg)
  17400. (save-restriction
  17401. (cond
  17402. ((or (equal arg '(16))
  17403. (and (equal arg '(4))
  17404. (org-with-limited-levels (org-before-first-heading-p))))
  17405. (if (org-remove-latex-fragment-image-overlays)
  17406. (progn (message "LaTeX fragments images removed from buffer")
  17407. (throw 'exit nil))
  17408. (setq msg "Creating images for buffer...")))
  17409. ((equal arg '(4))
  17410. (org-with-limited-levels (org-back-to-heading t))
  17411. (let ((beg (point))
  17412. (end (progn (org-end-of-subtree t) (point))))
  17413. (if (org-remove-latex-fragment-image-overlays beg end)
  17414. (progn
  17415. (message "LaTeX fragment images removed from subtree")
  17416. (throw 'exit nil))
  17417. (setq msg "Creating images for subtree...")
  17418. (narrow-to-region beg end))))
  17419. ((let ((datum (org-element-context)))
  17420. (when (memq (org-element-type datum)
  17421. '(latex-environment latex-fragment))
  17422. (let* ((beg (org-element-property :begin datum))
  17423. (end (org-element-property :end datum)))
  17424. (if (org-remove-latex-fragment-image-overlays beg end)
  17425. (progn (message "LaTeX fragment image removed")
  17426. (throw 'exit nil))
  17427. (narrow-to-region beg end)
  17428. (setq msg "Creating image..."))))))
  17429. (t
  17430. (org-with-limited-levels
  17431. (let ((beg (if (org-at-heading-p) (line-beginning-position)
  17432. (outline-previous-heading)
  17433. (point)))
  17434. (end (progn (outline-next-heading) (point))))
  17435. (if (org-remove-latex-fragment-image-overlays beg end)
  17436. (progn
  17437. (message "LaTeX fragment images removed from section")
  17438. (throw 'exit nil))
  17439. (setq msg "Creating images for section...")
  17440. (narrow-to-region beg end))))))
  17441. (let ((file (buffer-file-name (buffer-base-buffer))))
  17442. (org-format-latex
  17443. (concat org-latex-preview-ltxpng-directory
  17444. (file-name-sans-extension (file-name-nondirectory file)))
  17445. ;; Emacs cannot overlay images from remote hosts.
  17446. ;; Create it in `temporary-file-directory' instead.
  17447. (if (file-remote-p file) temporary-file-directory
  17448. default-directory)
  17449. 'overlays msg 'forbuffer
  17450. org-latex-create-formula-image-program)))
  17451. ;; Work around a bug that doesn't restore window's start
  17452. ;; when widening back the buffer.
  17453. (set-window-start nil window-start)
  17454. (message (concat msg "done")))))))
  17455. (defun org-format-latex
  17456. (prefix &optional dir overlays msg forbuffer processing-type)
  17457. "Replace LaTeX fragments with links to an image, and produce images.
  17458. When optional argument OVERLAYS is non-nil, display the image on
  17459. top of the fragment instead of replacing it.
  17460. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17461. Some of the options can be changed using the variable
  17462. `org-format-latex-options', which see."
  17463. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17464. (unless (eq processing-type 'verbatim)
  17465. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17466. (cnt 0)
  17467. checkdir-flag)
  17468. (goto-char (point-min))
  17469. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17470. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17471. (overlay-recenter (point-max)))
  17472. (while (re-search-forward math-regexp nil t)
  17473. (unless (and overlays
  17474. (eq (get-char-property (point) 'org-overlay-type)
  17475. 'org-latex-overlay))
  17476. (let* ((context (org-element-context))
  17477. (type (org-element-type context)))
  17478. (when (memq type '(latex-environment latex-fragment))
  17479. (let ((block-type (eq type 'latex-environment))
  17480. (value (org-element-property :value context))
  17481. (beg (org-element-property :begin context))
  17482. (end (save-excursion
  17483. (goto-char (org-element-property :end context))
  17484. (skip-chars-backward " \r\t\n")
  17485. (point))))
  17486. (case processing-type
  17487. (mathjax
  17488. ;; Prepare for MathJax processing.
  17489. (if (eq (char-after beg) ?$)
  17490. (save-excursion
  17491. (delete-region beg end)
  17492. (insert "\\(" (substring value 1 -1) "\\)"))
  17493. (goto-char end)))
  17494. ((dvipng imagemagick)
  17495. ;; Process to an image.
  17496. (incf cnt)
  17497. (goto-char beg)
  17498. (let* ((face (face-at-point))
  17499. ;; Get the colors from the face at point.
  17500. (fg
  17501. (let ((color (plist-get org-format-latex-options
  17502. :foreground)))
  17503. (if (and forbuffer (eq color 'auto))
  17504. (face-attribute face :foreground nil 'default)
  17505. color)))
  17506. (bg
  17507. (let ((color (plist-get org-format-latex-options
  17508. :background)))
  17509. (if (and forbuffer (eq color 'auto))
  17510. (face-attribute face :background nil 'default)
  17511. color)))
  17512. (hash (sha1 (prin1-to-string
  17513. (list org-format-latex-header
  17514. org-latex-default-packages-alist
  17515. org-latex-packages-alist
  17516. org-format-latex-options
  17517. forbuffer value fg bg))))
  17518. (absprefix (expand-file-name prefix dir))
  17519. (linkfile (format "%s_%s.png" prefix hash))
  17520. (movefile (format "%s_%s.png" absprefix hash))
  17521. (sep (and block-type "\n\n"))
  17522. (link (concat sep "[[file:" linkfile "]]" sep))
  17523. (options
  17524. (org-combine-plists
  17525. org-format-latex-options
  17526. `(:foreground ,fg :background ,bg))))
  17527. (when msg (message msg cnt))
  17528. (unless checkdir-flag ; Ensure the directory exists.
  17529. (setq checkdir-flag t)
  17530. (let ((todir (file-name-directory absprefix)))
  17531. (unless (file-directory-p todir)
  17532. (make-directory todir t))))
  17533. (unless (file-exists-p movefile)
  17534. (org-create-formula-image
  17535. value movefile options forbuffer processing-type))
  17536. (if overlays
  17537. (progn
  17538. (dolist (o (overlays-in beg end))
  17539. (when (eq (overlay-get o 'org-overlay-type)
  17540. 'org-latex-overlay)
  17541. (delete-overlay o)))
  17542. (let ((ov (make-overlay beg end)))
  17543. (overlay-put ov
  17544. 'org-overlay-type
  17545. 'org-latex-overlay)
  17546. (overlay-put ov 'evaporate t)
  17547. (if (featurep 'xemacs)
  17548. (progn
  17549. (overlay-put ov 'invisible t)
  17550. (overlay-put
  17551. ov 'end-glyph
  17552. (make-glyph
  17553. (vector 'png :file movefile))))
  17554. (overlay-put
  17555. ov 'display
  17556. (list 'image
  17557. :type 'png
  17558. :file movefile
  17559. :ascent 'center)))
  17560. (push ov org-latex-fragment-image-overlays))
  17561. (goto-char end))
  17562. (delete-region beg end)
  17563. (insert
  17564. (org-add-props link
  17565. (list 'org-latex-src
  17566. (replace-regexp-in-string "\"" "" value)
  17567. 'org-latex-src-embed-type
  17568. (if block-type 'paragraph 'character)))))))
  17569. (mathml
  17570. ;; Process to MathML.
  17571. (unless (org-format-latex-mathml-available-p)
  17572. (user-error "LaTeX to MathML converter not configured"))
  17573. (incf cnt)
  17574. (when msg (message msg cnt))
  17575. (goto-char beg)
  17576. (delete-region beg end)
  17577. (insert (org-format-latex-as-mathml
  17578. value block-type prefix dir)))
  17579. (otherwise
  17580. (error "Unknown conversion type %s for LaTeX fragments"
  17581. processing-type)))))))))))
  17582. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17583. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17584. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17585. sucessful, return the portion between \"<math...> </math>\"
  17586. elements otherwise return nil. When MATHML-FILE is specified,
  17587. write the results in to that file. When invoked as an
  17588. interactive command, prompt for LATEX-FRAG, with initial value
  17589. set to the current active region and echo the results for user
  17590. inspection."
  17591. (interactive (list (let ((frag (when (org-region-active-p)
  17592. (buffer-substring-no-properties
  17593. (region-beginning) (region-end)))))
  17594. (read-string "LaTeX Fragment: " frag nil frag))))
  17595. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17596. (let* ((tmp-in-file (file-relative-name
  17597. (make-temp-name (expand-file-name "ltxmathml-in"))))
  17598. (ignore (write-region latex-frag nil tmp-in-file))
  17599. (tmp-out-file (file-relative-name
  17600. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17601. (cmd (format-spec
  17602. org-latex-to-mathml-convert-command
  17603. `((?j . ,(and org-latex-to-mathml-jar-file
  17604. (shell-quote-argument
  17605. (expand-file-name
  17606. org-latex-to-mathml-jar-file))))
  17607. (?I . ,(shell-quote-argument tmp-in-file))
  17608. (?i . ,latex-frag)
  17609. (?o . ,(shell-quote-argument tmp-out-file)))))
  17610. mathml shell-command-output)
  17611. (when (org-called-interactively-p 'any)
  17612. (unless (org-format-latex-mathml-available-p)
  17613. (user-error "LaTeX to MathML converter not configured")))
  17614. (message "Running %s" cmd)
  17615. (setq shell-command-output (shell-command-to-string cmd))
  17616. (setq mathml
  17617. (when (file-readable-p tmp-out-file)
  17618. (with-current-buffer (find-file-noselect tmp-out-file t)
  17619. (goto-char (point-min))
  17620. (when (re-search-forward
  17621. (concat
  17622. (regexp-quote
  17623. "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
  17624. "[^>]*?>"
  17625. "\\(.\\|\n\\)*"
  17626. "</math>")
  17627. nil t)
  17628. (prog1 (match-string 0) (kill-buffer))))))
  17629. (cond
  17630. (mathml
  17631. (setq mathml
  17632. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17633. (when mathml-file
  17634. (write-region mathml nil mathml-file))
  17635. (when (org-called-interactively-p 'any)
  17636. (message mathml)))
  17637. ((message "LaTeX to MathML conversion failed")
  17638. (message shell-command-output)))
  17639. (delete-file tmp-in-file)
  17640. (when (file-exists-p tmp-out-file)
  17641. (delete-file tmp-out-file))
  17642. mathml))
  17643. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17644. prefix &optional dir)
  17645. "Use `org-create-math-formula' but check local cache first."
  17646. (let* ((absprefix (expand-file-name prefix dir))
  17647. (print-length nil) (print-level nil)
  17648. (formula-id (concat
  17649. "formula-"
  17650. (sha1
  17651. (prin1-to-string
  17652. (list latex-frag
  17653. org-latex-to-mathml-convert-command)))))
  17654. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17655. (formula-cache-dir (file-name-directory formula-cache)))
  17656. (unless (file-directory-p formula-cache-dir)
  17657. (make-directory formula-cache-dir t))
  17658. (unless (file-exists-p formula-cache)
  17659. (org-create-math-formula latex-frag formula-cache))
  17660. (if (file-exists-p formula-cache)
  17661. ;; Successful conversion. Return the link to MathML file.
  17662. (org-add-props
  17663. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17664. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17665. 'org-latex-src-embed-type (if latex-frag-type
  17666. 'paragraph 'character)))
  17667. ;; Failed conversion. Return the LaTeX fragment verbatim
  17668. latex-frag)))
  17669. (defun org-create-formula-image (string tofile options buffer &optional type)
  17670. "Create an image from LaTeX source using dvipng or convert.
  17671. This function calls either `org-create-formula-image-with-dvipng'
  17672. or `org-create-formula-image-with-imagemagick' depending on the
  17673. value of `org-latex-create-formula-image-program' or on the value
  17674. of the optional TYPE variable.
  17675. Note: ultimately these two function should be combined as they
  17676. share a good deal of logic."
  17677. (org-check-external-command
  17678. "latex" "needed to convert LaTeX fragments to images")
  17679. (funcall
  17680. (case (or type org-latex-create-formula-image-program)
  17681. (dvipng
  17682. (org-check-external-command
  17683. "dvipng" "needed to convert LaTeX fragments to images")
  17684. #'org-create-formula-image-with-dvipng)
  17685. (imagemagick
  17686. (org-check-external-command
  17687. "convert" "you need to install imagemagick")
  17688. #'org-create-formula-image-with-imagemagick)
  17689. (t (error
  17690. "Invalid value of `org-latex-create-formula-image-program'")))
  17691. string tofile options buffer))
  17692. (declare-function org-export-get-backend "ox" (name))
  17693. (declare-function org-export--get-global-options "ox" (&optional backend))
  17694. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17695. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17696. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17697. (defun org-create-formula--latex-header ()
  17698. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17699. (let ((info (org-combine-plists (org-export--get-global-options
  17700. (org-export-get-backend 'latex))
  17701. (org-export--get-inbuffer-options
  17702. (org-export-get-backend 'latex)))))
  17703. (org-latex-guess-babel-language
  17704. (org-latex-guess-inputenc
  17705. (org-splice-latex-header
  17706. org-format-latex-header
  17707. org-latex-default-packages-alist
  17708. org-latex-packages-alist t
  17709. (plist-get info :latex-header)))
  17710. info)))
  17711. (defun org--get-display-dpi ()
  17712. "Get the DPI of the display.
  17713. Assumes that the display has the same pixel width in the
  17714. horizontal and vertical directions."
  17715. (if (display-graphic-p)
  17716. (round (/ (display-pixel-height)
  17717. (/ (display-mm-height) 25.4)))
  17718. (error "Attempt to calculate the dpi of a non-graphic display")))
  17719. ;; This function borrows from Ganesh Swami's latex2png.el
  17720. (defun org-create-formula-image-with-dvipng (string tofile options buffer)
  17721. "This calls dvipng."
  17722. (require 'ox-latex)
  17723. (let* ((tmpdir (if (featurep 'xemacs)
  17724. (temp-directory)
  17725. temporary-file-directory))
  17726. (texfilebase (make-temp-name
  17727. (expand-file-name "orgtex" tmpdir)))
  17728. (texfile (concat texfilebase ".tex"))
  17729. (dvifile (concat texfilebase ".dvi"))
  17730. (pngfile (concat texfilebase ".png"))
  17731. (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
  17732. ;; This assumes that the display has the same pixel width in
  17733. ;; the horizontal and vertical directions
  17734. (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
  17735. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17736. "Black"))
  17737. (bg (or (plist-get options (if buffer :background :html-background))
  17738. "Transparent")))
  17739. (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
  17740. (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
  17741. (if (eq bg 'default) (setq bg (org-dvipng-color :background))
  17742. (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
  17743. (let ((latex-header (org-create-formula--latex-header)))
  17744. (with-temp-file texfile
  17745. (insert latex-header)
  17746. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17747. (let ((dir default-directory))
  17748. (ignore-errors
  17749. (cd tmpdir)
  17750. (call-process "latex" nil nil nil texfile))
  17751. (cd dir))
  17752. (if (not (file-exists-p dvifile))
  17753. (progn (message "Failed to create dvi file from %s" texfile) nil)
  17754. (ignore-errors
  17755. (if (featurep 'xemacs)
  17756. (call-process "dvipng" nil nil nil
  17757. "-fg" fg "-bg" bg
  17758. "-T" "tight"
  17759. "-o" pngfile
  17760. dvifile)
  17761. (call-process "dvipng" nil nil nil
  17762. "-fg" fg "-bg" bg
  17763. "-D" dpi
  17764. ;;"-x" scale "-y" scale
  17765. "-T" "tight"
  17766. "-o" pngfile
  17767. dvifile)))
  17768. (if (not (file-exists-p pngfile))
  17769. (if org-format-latex-signal-error
  17770. (error "Failed to create png file from %s" texfile)
  17771. (message "Failed to create png file from %s" texfile)
  17772. nil)
  17773. ;; Use the requested file name and clean up
  17774. (copy-file pngfile tofile 'replace)
  17775. (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
  17776. (when (file-exists-p (concat texfilebase e))
  17777. (delete-file (concat texfilebase e))))
  17778. pngfile))))
  17779. (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
  17780. (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
  17781. "This calls convert, which is included into imagemagick."
  17782. (require 'ox-latex)
  17783. (let* ((tmpdir (if (featurep 'xemacs)
  17784. (temp-directory)
  17785. temporary-file-directory))
  17786. (texfilebase (make-temp-name
  17787. (expand-file-name "orgtex" tmpdir)))
  17788. (texfile (concat texfilebase ".tex"))
  17789. (pdffile (concat texfilebase ".pdf"))
  17790. (pngfile (concat texfilebase ".png"))
  17791. (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
  17792. (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
  17793. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17794. "black"))
  17795. (bg (or (plist-get options (if buffer :background :html-background))
  17796. "white")))
  17797. (if (eq fg 'default) (setq fg (org-latex-color :foreground))
  17798. (setq fg (org-latex-color-format fg)))
  17799. (if (eq bg 'default) (setq bg (org-latex-color :background))
  17800. (setq bg (org-latex-color-format
  17801. (if (string= bg "Transparent") "white" bg))))
  17802. (let ((latex-header (org-create-formula--latex-header)))
  17803. (with-temp-file texfile
  17804. (insert latex-header)
  17805. (insert "\n\\begin{document}\n"
  17806. "\\definecolor{fg}{rgb}{" fg "}\n"
  17807. "\\definecolor{bg}{rgb}{" bg "}\n"
  17808. "\n\\pagecolor{bg}\n"
  17809. "\n{\\color{fg}\n"
  17810. string
  17811. "\n}\n"
  17812. "\n\\end{document}\n")))
  17813. (org-latex-compile texfile t)
  17814. (if (not (file-exists-p pdffile))
  17815. (progn (message "Failed to create pdf file from %s" texfile) nil)
  17816. (ignore-errors
  17817. (if (featurep 'xemacs)
  17818. (call-process "convert" nil nil nil
  17819. "-density" "96"
  17820. "-trim"
  17821. "-antialias"
  17822. pdffile
  17823. "-quality" "100"
  17824. ;; "-sharpen" "0x1.0"
  17825. pngfile)
  17826. (call-process "convert" nil nil nil
  17827. "-density" dpi
  17828. "-trim"
  17829. "-antialias"
  17830. pdffile
  17831. "-quality" "100"
  17832. ;; "-sharpen" "0x1.0"
  17833. pngfile)))
  17834. (if (not (file-exists-p pngfile))
  17835. (if org-format-latex-signal-error
  17836. (error "Failed to create png file from %s" texfile)
  17837. (message "Failed to create png file from %s" texfile)
  17838. nil)
  17839. ;; Use the requested file name and clean up
  17840. (copy-file pngfile tofile 'replace)
  17841. (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
  17842. (when (file-exists-p (concat texfilebase e))
  17843. (delete-file (concat texfilebase e))))
  17844. pngfile))))
  17845. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17846. "Fill a LaTeX header template TPL.
  17847. In the template, the following place holders will be recognized:
  17848. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17849. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17850. [PACKAGES] \\usepackage statements for PKG
  17851. [NO-PACKAGES] do not include PKG
  17852. [EXTRA] the string EXTRA
  17853. [NO-EXTRA] do not include EXTRA
  17854. For backward compatibility, if both the positive and the negative place
  17855. holder is missing, the positive one (without the \"NO-\") will be
  17856. assumed to be present at the end of the template.
  17857. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17858. EXTRA is a string.
  17859. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17860. (let (rpl (end ""))
  17861. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17862. (setq rpl (if (or (match-end 1) (not def-pkg))
  17863. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17864. tpl (replace-match rpl t t tpl))
  17865. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17866. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17867. (setq rpl (if (or (match-end 1) (not pkg))
  17868. "" (org-latex-packages-to-string pkg snippets-p t))
  17869. tpl (replace-match rpl t t tpl))
  17870. (when pkg (setq end
  17871. (concat end "\n"
  17872. (org-latex-packages-to-string pkg snippets-p)))))
  17873. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17874. (setq rpl (if (or (match-end 1) (not extra))
  17875. "" (concat extra "\n"))
  17876. tpl (replace-match rpl t t tpl))
  17877. (when (and extra (string-match "\\S-" extra))
  17878. (setq end (concat end "\n" extra))))
  17879. (if (string-match "\\S-" end)
  17880. (concat tpl "\n" end)
  17881. tpl)))
  17882. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17883. "Turn an alist of packages into a string with the \\usepackage macros."
  17884. (setq pkg (mapconcat (lambda(p)
  17885. (cond
  17886. ((stringp p) p)
  17887. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17888. (format "%% Package %s omitted" (cadr p)))
  17889. ((equal "" (car p))
  17890. (format "\\usepackage{%s}" (cadr p)))
  17891. (t
  17892. (format "\\usepackage[%s]{%s}"
  17893. (car p) (cadr p)))))
  17894. pkg
  17895. "\n"))
  17896. (if newline (concat pkg "\n") pkg))
  17897. (defun org-dvipng-color (attr)
  17898. "Return a RGB color specification for dvipng."
  17899. (apply 'format "rgb %s %s %s"
  17900. (mapcar 'org-normalize-color
  17901. (if (featurep 'xemacs)
  17902. (color-rgb-components
  17903. (face-property 'default
  17904. (cond ((eq attr :foreground) 'foreground)
  17905. ((eq attr :background) 'background))))
  17906. (color-values (face-attribute 'default attr nil))))))
  17907. (defun org-dvipng-color-format (color-name)
  17908. "Convert COLOR-NAME to a RGB color value for dvipng."
  17909. (apply 'format "rgb %s %s %s"
  17910. (mapcar 'org-normalize-color
  17911. (color-values color-name))))
  17912. (defun org-latex-color (attr)
  17913. "Return a RGB color for the LaTeX color package."
  17914. (apply 'format "%s,%s,%s"
  17915. (mapcar 'org-normalize-color
  17916. (if (featurep 'xemacs)
  17917. (color-rgb-components
  17918. (face-property 'default
  17919. (cond ((eq attr :foreground) 'foreground)
  17920. ((eq attr :background) 'background))))
  17921. (color-values (face-attribute 'default attr nil))))))
  17922. (defun org-latex-color-format (color-name)
  17923. "Convert COLOR-NAME to a RGB color value."
  17924. (apply 'format "%s,%s,%s"
  17925. (mapcar 'org-normalize-color
  17926. (color-values color-name))))
  17927. (defun org-normalize-color (value)
  17928. "Return string to be used as color value for an RGB component."
  17929. (format "%g" (/ value 65535.0)))
  17930. ;; Image display
  17931. (defvar-local org-inline-image-overlays nil)
  17932. (defun org-toggle-inline-images (&optional include-linked)
  17933. "Toggle the display of inline images.
  17934. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17935. (interactive "P")
  17936. (if org-inline-image-overlays
  17937. (progn
  17938. (org-remove-inline-images)
  17939. (when (org-called-interactively-p 'interactive)
  17940. (message "Inline image display turned off")))
  17941. (org-display-inline-images include-linked)
  17942. (when (org-called-interactively-p 'interactive)
  17943. (message (if org-inline-image-overlays
  17944. (format "%d images displayed inline"
  17945. (length org-inline-image-overlays))
  17946. "No images to display inline")))))
  17947. (defun org-redisplay-inline-images ()
  17948. "Refresh the display of inline images."
  17949. (interactive)
  17950. (if (not org-inline-image-overlays)
  17951. (org-toggle-inline-images)
  17952. (org-toggle-inline-images)
  17953. (org-toggle-inline-images)))
  17954. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17955. "Display inline images.
  17956. An inline image is a link which follows either of these
  17957. conventions:
  17958. 1. Its path is a file with an extension matching return value
  17959. from `image-file-name-regexp' and it has no contents.
  17960. 2. Its description consists in a single link of the previous
  17961. type.
  17962. When optional argument INCLUDE-LINKED is non-nil, also links with
  17963. a text description part will be inlined. This can be nice for
  17964. a quick look at those images, but it does not reflect what
  17965. exported files will look like.
  17966. When optional argument REFRESH is non-nil, refresh existing
  17967. images between BEG and END. This will create new image displays
  17968. only if necessary. BEG and END default to the buffer
  17969. boundaries."
  17970. (interactive "P")
  17971. (when (display-graphic-p)
  17972. (unless refresh
  17973. (org-remove-inline-images)
  17974. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17975. (org-with-wide-buffer
  17976. (goto-char (or beg (point-min)))
  17977. (let ((case-fold-search t)
  17978. (file-extension-re (image-file-name-regexp)))
  17979. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17980. (let ((link (save-match-data (org-element-context))))
  17981. ;; Check if we're at an inline image.
  17982. (when (and (equal (org-element-property :type link) "file")
  17983. (or include-linked
  17984. (not (org-element-property :contents-begin link)))
  17985. (let ((parent (org-element-property :parent link)))
  17986. (or (not (eq (org-element-type parent) 'link))
  17987. (not (cdr (org-element-contents parent)))))
  17988. (org-string-match-p file-extension-re
  17989. (org-element-property :path link)))
  17990. (let ((file (expand-file-name
  17991. (org-link-unescape
  17992. (org-element-property :path link)))))
  17993. (when (file-exists-p file)
  17994. (let ((width
  17995. ;; Apply `org-image-actual-width' specifications.
  17996. (cond
  17997. ((not (image-type-available-p 'imagemagick)) nil)
  17998. ((eq org-image-actual-width t) nil)
  17999. ((listp org-image-actual-width)
  18000. (or
  18001. ;; First try to find a width among
  18002. ;; attributes associated to the paragraph
  18003. ;; containing link.
  18004. (let ((paragraph
  18005. (let ((e link))
  18006. (while (and (setq e (org-element-property
  18007. :parent e))
  18008. (not (eq (org-element-type e)
  18009. 'paragraph))))
  18010. e)))
  18011. (when paragraph
  18012. (save-excursion
  18013. (goto-char (org-element-property :begin paragraph))
  18014. (when
  18015. (re-search-forward
  18016. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  18017. (org-element-property
  18018. :post-affiliated paragraph)
  18019. t)
  18020. (string-to-number (match-string 1))))))
  18021. ;; Otherwise, fall-back to provided number.
  18022. (car org-image-actual-width)))
  18023. ((numberp org-image-actual-width)
  18024. org-image-actual-width)))
  18025. (old (get-char-property-and-overlay
  18026. (org-element-property :begin link)
  18027. 'org-image-overlay)))
  18028. (if (and (car-safe old) refresh)
  18029. (image-refresh (overlay-get (cdr old) 'display))
  18030. (let ((image (create-image file
  18031. (and width 'imagemagick)
  18032. nil
  18033. :width width)))
  18034. (when image
  18035. (let* ((link
  18036. ;; If inline image is the description
  18037. ;; of another link, be sure to
  18038. ;; consider the latter as the one to
  18039. ;; apply the overlay on.
  18040. (let ((parent
  18041. (org-element-property :parent link)))
  18042. (if (eq (org-element-type parent) 'link)
  18043. parent
  18044. link)))
  18045. (ov (make-overlay
  18046. (org-element-property :begin link)
  18047. (progn
  18048. (goto-char
  18049. (org-element-property :end link))
  18050. (skip-chars-backward " \t")
  18051. (point)))))
  18052. (overlay-put ov 'display image)
  18053. (overlay-put ov 'face 'default)
  18054. (overlay-put ov 'org-image-overlay t)
  18055. (overlay-put
  18056. ov 'modification-hooks
  18057. (list 'org-display-inline-remove-overlay))
  18058. (push ov org-inline-image-overlays)))))))))))))))
  18059. (define-obsolete-function-alias
  18060. 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
  18061. (defun org-display-inline-remove-overlay (ov after beg end &optional len)
  18062. "Remove inline-display overlay if a corresponding region is modified."
  18063. (let ((inhibit-modification-hooks t))
  18064. (when (and ov after)
  18065. (delete ov org-inline-image-overlays)
  18066. (delete-overlay ov))))
  18067. (defun org-remove-inline-images ()
  18068. "Remove inline display of images."
  18069. (interactive)
  18070. (mapc 'delete-overlay org-inline-image-overlays)
  18071. (setq org-inline-image-overlays nil))
  18072. ;;;; Key bindings
  18073. ;; Outline functions from `outline-mode-prefix-map'
  18074. ;; that can be remapped in Org:
  18075. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18076. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18077. (define-key org-mode-map [remap outline-forward-same-level]
  18078. 'org-forward-heading-same-level)
  18079. (define-key org-mode-map [remap outline-backward-same-level]
  18080. 'org-backward-heading-same-level)
  18081. (define-key org-mode-map [remap outline-show-branches]
  18082. 'org-kill-note-or-show-branches)
  18083. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18084. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18085. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18086. (define-key org-mode-map [remap outline-next-visible-heading]
  18087. 'org-next-visible-heading)
  18088. (define-key org-mode-map [remap outline-previous-visible-heading]
  18089. 'org-previous-visible-heading)
  18090. (define-key org-mode-map [remap show-children] 'org-show-children)
  18091. ;; Outline functions from `outline-mode-prefix-map' that can not
  18092. ;; be remapped in Org:
  18093. ;; - the column "key binding" shows whether the Outline function is still
  18094. ;; available in Org mode on the same key that it has been bound to in
  18095. ;; Outline mode:
  18096. ;; - "overridden": key used for a different functionality in Org mode
  18097. ;; - else: key still bound to the same Outline function in Org mode
  18098. ;; | Outline function | key binding | Org replacement |
  18099. ;; |------------------------------------+-------------+--------------------------|
  18100. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18101. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18102. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18103. ;; | `show-entry' | overridden | no replacement |
  18104. ;; | `show-branches' | `C-c C-k' | still same function |
  18105. ;; | `show-subtree' | overridden | visibility cycling |
  18106. ;; | `show-all' | overridden | no replacement |
  18107. ;; | `hide-subtree' | overridden | visibility cycling |
  18108. ;; | `hide-body' | overridden | no replacement |
  18109. ;; | `hide-entry' | overridden | visibility cycling |
  18110. ;; | `hide-leaves' | overridden | no replacement |
  18111. ;; | `hide-sublevels' | overridden | no replacement |
  18112. ;; | `hide-other' | overridden | no replacement |
  18113. ;; Make `C-c C-x' a prefix key
  18114. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18115. ;; TAB key with modifiers
  18116. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18117. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18118. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18119. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18120. ;; The following line is necessary under Suse GNU/Linux
  18121. (unless (featurep 'xemacs)
  18122. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
  18123. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18124. (define-key org-mode-map [backtab] 'org-shifttab)
  18125. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18126. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18127. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18128. ;; Cursor keys with modifiers
  18129. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18130. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18131. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18132. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18133. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18134. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18135. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18136. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18137. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18138. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18139. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18140. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18141. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18142. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18143. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18144. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18145. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18146. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18147. ;; Babel keys
  18148. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18149. (mapc (lambda (pair)
  18150. (define-key org-babel-map (car pair) (cdr pair)))
  18151. org-babel-key-bindings)
  18152. ;;; Extra keys for tty access.
  18153. ;; We only set them when really needed because otherwise the
  18154. ;; menus don't show the simple keys
  18155. (when (or org-use-extra-keys
  18156. (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
  18157. (not window-system))
  18158. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18159. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18160. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18161. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18162. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18163. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18164. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18165. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18166. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18167. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18168. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18169. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18170. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18171. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18172. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18173. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18174. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18175. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18176. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18177. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18178. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18179. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18180. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18181. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18182. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18183. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18184. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18185. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18186. ;; All the other keys
  18187. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18188. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18189. (if (boundp 'narrow-map)
  18190. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18191. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18192. (if (boundp 'narrow-map)
  18193. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18194. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18195. (if (boundp 'narrow-map)
  18196. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18197. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18198. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18199. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18200. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18201. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18202. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18203. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18204. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18205. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18206. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18207. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18208. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18209. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18210. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18211. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18212. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18213. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18214. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18215. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18216. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18217. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18218. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18219. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18220. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18221. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18222. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18223. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18224. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18225. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18226. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18227. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18228. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18229. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18230. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18231. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18232. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18233. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18234. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18235. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18236. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18237. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18238. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18239. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18240. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18241. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18242. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18243. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18244. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18245. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18246. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18247. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18248. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18249. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18250. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18251. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18252. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18253. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18254. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18255. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18256. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18257. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18258. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18259. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18260. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18261. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18262. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18263. (org-defkey org-mode-map "\C-m" 'org-return)
  18264. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18265. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18266. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18267. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18268. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18269. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18270. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18271. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18272. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18273. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18274. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18275. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18276. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18277. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18278. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18279. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18280. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18281. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18282. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18283. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18284. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18285. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18286. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18287. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18288. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18289. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18290. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18291. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18292. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18293. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18294. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18295. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18296. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18297. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18298. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18299. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18300. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18301. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18302. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18303. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18304. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18305. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18306. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18307. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18308. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18309. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18310. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18311. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18312. (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
  18313. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18314. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18315. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18316. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18317. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18318. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18319. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18320. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18321. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18322. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18323. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18324. (when (featurep 'xemacs)
  18325. (org-defkey org-mode-map 'button3 'popup-mode-menu))
  18326. (defconst org-speed-commands-default
  18327. '(
  18328. ("Outline Navigation")
  18329. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18330. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18331. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18332. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18333. ("F" . org-next-block)
  18334. ("B" . org-previous-block)
  18335. ("u" . (org-speed-move-safe 'outline-up-heading))
  18336. ("j" . org-goto)
  18337. ("g" . (org-refile t))
  18338. ("Outline Visibility")
  18339. ("c" . org-cycle)
  18340. ("C" . org-shifttab)
  18341. (" " . org-display-outline-path)
  18342. ("s" . org-narrow-to-subtree)
  18343. ("=" . org-columns)
  18344. ("Outline Structure Editing")
  18345. ("U" . org-metaup)
  18346. ("D" . org-metadown)
  18347. ("r" . org-metaright)
  18348. ("l" . org-metaleft)
  18349. ("R" . org-shiftmetaright)
  18350. ("L" . org-shiftmetaleft)
  18351. ("i" . (progn (forward-char 1) (call-interactively
  18352. 'org-insert-heading-respect-content)))
  18353. ("^" . org-sort)
  18354. ("w" . org-refile)
  18355. ("a" . org-archive-subtree-default-with-confirmation)
  18356. ("@" . org-mark-subtree)
  18357. ("#" . org-toggle-comment)
  18358. ("Clock Commands")
  18359. ("I" . org-clock-in)
  18360. ("O" . org-clock-out)
  18361. ("Meta Data Editing")
  18362. ("t" . org-todo)
  18363. ("," . (org-priority))
  18364. ("0" . (org-priority ?\ ))
  18365. ("1" . (org-priority ?A))
  18366. ("2" . (org-priority ?B))
  18367. ("3" . (org-priority ?C))
  18368. (":" . org-set-tags-command)
  18369. ("e" . org-set-effort)
  18370. ("E" . org-inc-effort)
  18371. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18372. (org-entry-put (point) "APPT_WARNTIME" m)))
  18373. ("Agenda Views etc")
  18374. ("v" . org-agenda)
  18375. ("/" . org-sparse-tree)
  18376. ("Misc")
  18377. ("o" . org-open-at-point)
  18378. ("?" . org-speed-command-help)
  18379. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18380. (">" . (org-agenda-remove-restriction-lock))
  18381. )
  18382. "The default speed commands.")
  18383. (defun org-print-speed-command (e)
  18384. (if (> (length (car e)) 1)
  18385. (progn
  18386. (princ "\n")
  18387. (princ (car e))
  18388. (princ "\n")
  18389. (princ (make-string (length (car e)) ?-))
  18390. (princ "\n"))
  18391. (princ (car e))
  18392. (princ " ")
  18393. (if (symbolp (cdr e))
  18394. (princ (symbol-name (cdr e)))
  18395. (prin1 (cdr e)))
  18396. (princ "\n")))
  18397. (defun org-speed-command-help ()
  18398. "Show the available speed commands."
  18399. (interactive)
  18400. (if (not org-use-speed-commands)
  18401. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18402. (with-output-to-temp-buffer "*Help*"
  18403. (princ "User-defined Speed commands\n===========================\n")
  18404. (mapc 'org-print-speed-command org-speed-commands-user)
  18405. (princ "\n")
  18406. (princ "Built-in Speed commands\n=======================\n")
  18407. (mapc 'org-print-speed-command org-speed-commands-default))
  18408. (with-current-buffer "*Help*"
  18409. (setq truncate-lines t))))
  18410. (defun org-speed-move-safe (cmd)
  18411. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18412. If not, return to the original position and throw an error."
  18413. (interactive)
  18414. (let ((pos (point)))
  18415. (call-interactively cmd)
  18416. (unless (and (bolp) (org-at-heading-p))
  18417. (goto-char pos)
  18418. (error "Boundary reached while executing %s" cmd))))
  18419. (defvar org-self-insert-command-undo-counter 0)
  18420. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18421. (defvar org-speed-command nil)
  18422. (define-obsolete-function-alias
  18423. 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
  18424. (defun org-speed-command-activate (keys)
  18425. "Hook for activating single-letter speed commands.
  18426. `org-speed-commands-default' specifies a minimal command set.
  18427. Use `org-speed-commands-user' for further customization."
  18428. (when (or (and (bolp) (looking-at org-outline-regexp))
  18429. (and (functionp org-use-speed-commands)
  18430. (funcall org-use-speed-commands)))
  18431. (cdr (assoc keys (append org-speed-commands-user
  18432. org-speed-commands-default)))))
  18433. (define-obsolete-function-alias
  18434. 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
  18435. (defun org-babel-speed-command-activate (keys)
  18436. "Hook for activating single-letter code block commands."
  18437. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18438. (cdr (assoc keys org-babel-key-bindings))))
  18439. (defcustom org-speed-command-hook
  18440. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18441. "Hook for activating speed commands at strategic locations.
  18442. Hook functions are called in sequence until a valid handler is
  18443. found.
  18444. Each hook takes a single argument, a user-pressed command key
  18445. which is also a `self-insert-command' from the global map.
  18446. Within the hook, examine the cursor position and the command key
  18447. and return nil or a valid handler as appropriate. Handler could
  18448. be one of an interactive command, a function, or a form.
  18449. Set `org-use-speed-commands' to non-nil value to enable this
  18450. hook. The default setting is `org-speed-command-activate'."
  18451. :group 'org-structure
  18452. :version "24.1"
  18453. :type 'hook)
  18454. (defun org-self-insert-command (N)
  18455. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18456. If the cursor is in a table looking at whitespace, the whitespace is
  18457. overwritten, and the table is not marked as requiring realignment."
  18458. (interactive "p")
  18459. (org-check-before-invisible-edit 'insert)
  18460. (cond
  18461. ((and org-use-speed-commands
  18462. (let ((kv (this-command-keys-vector)))
  18463. (setq org-speed-command
  18464. (run-hook-with-args-until-success
  18465. 'org-speed-command-hook
  18466. (make-string 1 (aref kv (1- (length kv))))))))
  18467. (cond
  18468. ((commandp org-speed-command)
  18469. (setq this-command org-speed-command)
  18470. (call-interactively org-speed-command))
  18471. ((functionp org-speed-command)
  18472. (funcall org-speed-command))
  18473. ((and org-speed-command (listp org-speed-command))
  18474. (eval org-speed-command))
  18475. (t (let (org-use-speed-commands)
  18476. (call-interactively 'org-self-insert-command)))))
  18477. ((and
  18478. (org-at-table-p)
  18479. (progn
  18480. ;; Check if we blank the field, and if that triggers align.
  18481. (and (featurep 'org-table) org-table-auto-blank-field
  18482. (memq last-command
  18483. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18484. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18485. ;; Got extra space, this field does not determine
  18486. ;; column width.
  18487. (let (org-table-may-need-update) (org-table-blank-field))
  18488. ;; No extra space, this field may determine column
  18489. ;; width.
  18490. (org-table-blank-field)))
  18491. t)
  18492. (eq N 1)
  18493. (looking-at "[^|\n]* \\( \\)|"))
  18494. ;; There is room for insertion without re-aligning the table.
  18495. (delete-region (match-beginning 1) (match-end 1))
  18496. (self-insert-command N))
  18497. (t
  18498. (setq org-table-may-need-update t)
  18499. (self-insert-command N)
  18500. (org-fix-tags-on-the-fly)
  18501. (when org-self-insert-cluster-for-undo
  18502. (if (not (eq last-command 'org-self-insert-command))
  18503. (setq org-self-insert-command-undo-counter 1)
  18504. (if (>= org-self-insert-command-undo-counter 20)
  18505. (setq org-self-insert-command-undo-counter 1)
  18506. (and (> org-self-insert-command-undo-counter 0)
  18507. buffer-undo-list (listp buffer-undo-list)
  18508. (not (cadr buffer-undo-list)) ; remove nil entry
  18509. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18510. (setq org-self-insert-command-undo-counter
  18511. (1+ org-self-insert-command-undo-counter))))))))
  18512. (defun org-check-before-invisible-edit (kind)
  18513. "Check is editing if kind KIND would be dangerous with invisible text around.
  18514. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18515. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18516. (when (and org-catch-invisible-edits
  18517. (or (not (boundp 'visible-mode)) (not visible-mode))
  18518. (or (get-char-property (point) 'invisible)
  18519. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18520. ;; OK, we need to take a closer look
  18521. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18522. (invisible-before-point (unless (bobp) (get-char-property
  18523. (1- (point)) 'invisible)))
  18524. (border-and-ok-direction
  18525. (or
  18526. ;; Check if we are acting predictably before invisible text
  18527. (and invisible-at-point (not invisible-before-point)
  18528. (memq kind '(insert delete-backward)))
  18529. ;; Check if we are acting predictably after invisible text
  18530. ;; This works not well, and I have turned it off. It seems
  18531. ;; better to always show and stop after invisible text.
  18532. ;; (and (not invisible-at-point) invisible-before-point
  18533. ;; (memq kind '(insert delete)))
  18534. )))
  18535. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18536. (memq invisible-before-point '(outline org-hide-block t)))
  18537. (when (eq org-catch-invisible-edits 'error)
  18538. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18539. (if (and org-custom-properties-overlays
  18540. (y-or-n-p "Display invisible properties in this buffer? "))
  18541. (org-toggle-custom-properties-visibility)
  18542. ;; Make the area visible
  18543. (save-excursion
  18544. (when invisible-before-point
  18545. (goto-char (previous-single-char-property-change
  18546. (point) 'invisible)))
  18547. (outline-show-subtree))
  18548. (cond
  18549. ((eq org-catch-invisible-edits 'show)
  18550. ;; That's it, we do the edit after showing
  18551. (message
  18552. "Unfolding invisible region around point before editing")
  18553. (sit-for 1))
  18554. ((and (eq org-catch-invisible-edits 'smart)
  18555. border-and-ok-direction)
  18556. (message "Unfolding invisible region around point before editing"))
  18557. (t
  18558. ;; Don't do the edit, make the user repeat it in full visibility
  18559. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18560. (defun org-fix-tags-on-the-fly ()
  18561. (when (and (equal (char-after (point-at-bol)) ?*)
  18562. (org-at-heading-p))
  18563. (org-align-tags-here org-tags-column)))
  18564. (defun org-delete-backward-char (N)
  18565. "Like `delete-backward-char', insert whitespace at field end in tables.
  18566. When deleting backwards, in tables this function will insert whitespace in
  18567. front of the next \"|\" separator, to keep the table aligned. The table will
  18568. still be marked for re-alignment if the field did fill the entire column,
  18569. because, in this case the deletion might narrow the column."
  18570. (interactive "p")
  18571. (save-match-data
  18572. (org-check-before-invisible-edit 'delete-backward)
  18573. (if (and (org-at-table-p)
  18574. (eq N 1)
  18575. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18576. (looking-at ".*?|"))
  18577. (let ((pos (point))
  18578. (noalign (looking-at "[^|\n\r]* |"))
  18579. (c org-table-may-need-update))
  18580. (backward-delete-char N)
  18581. (unless overwrite-mode
  18582. (skip-chars-forward "^|")
  18583. (insert " ")
  18584. (goto-char (1- pos)))
  18585. ;; noalign: if there were two spaces at the end, this field
  18586. ;; does not determine the width of the column.
  18587. (when noalign (setq org-table-may-need-update c)))
  18588. (backward-delete-char N)
  18589. (org-fix-tags-on-the-fly))))
  18590. (defun org-delete-char (N)
  18591. "Like `delete-char', but insert whitespace at field end in tables.
  18592. When deleting characters, in tables this function will insert whitespace in
  18593. front of the next \"|\" separator, to keep the table aligned. The table will
  18594. still be marked for re-alignment if the field did fill the entire column,
  18595. because, in this case the deletion might narrow the column."
  18596. (interactive "p")
  18597. (save-match-data
  18598. (org-check-before-invisible-edit 'delete)
  18599. (if (and (org-at-table-p)
  18600. (not (bolp))
  18601. (not (= (char-after) ?|))
  18602. (eq N 1))
  18603. (if (looking-at ".*?|")
  18604. (let ((pos (point))
  18605. (noalign (looking-at "[^|\n\r]* |"))
  18606. (c org-table-may-need-update))
  18607. (replace-match
  18608. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18609. (goto-char pos)
  18610. ;; noalign: if there were two spaces at the end, this field
  18611. ;; does not determine the width of the column.
  18612. (when noalign (setq org-table-may-need-update c)))
  18613. (delete-char N))
  18614. (delete-char N)
  18615. (org-fix-tags-on-the-fly))))
  18616. ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
  18617. (put 'org-self-insert-command 'delete-selection
  18618. (lambda ()
  18619. (not (run-hook-with-args-until-success
  18620. 'self-insert-uses-region-functions))))
  18621. (put 'orgtbl-self-insert-command 'delete-selection
  18622. (lambda ()
  18623. (not (run-hook-with-args-until-success
  18624. 'self-insert-uses-region-functions))))
  18625. (put 'org-delete-char 'delete-selection 'supersede)
  18626. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18627. (put 'org-yank 'delete-selection 'yank)
  18628. ;; Make `flyspell-mode' delay after some commands
  18629. (put 'org-self-insert-command 'flyspell-delayed t)
  18630. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18631. (put 'org-delete-char 'flyspell-delayed t)
  18632. (put 'org-delete-backward-char 'flyspell-delayed t)
  18633. ;; Make pabbrev-mode expand after org-mode commands
  18634. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18635. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18636. (defun org-remap (map &rest commands)
  18637. "In MAP, remap the functions given in COMMANDS.
  18638. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18639. (let (new old)
  18640. (while commands
  18641. (setq old (pop commands) new (pop commands))
  18642. (if (fboundp 'command-remapping)
  18643. (org-defkey map (vector 'remap old) new)
  18644. (substitute-key-definition old new map global-map)))))
  18645. (defun org-transpose-words ()
  18646. "Transpose words for Org.
  18647. This uses the `org-mode-transpose-word-syntax-table' syntax
  18648. table, which interprets characters in `org-emphasis-alist' as
  18649. word constituents."
  18650. (interactive)
  18651. (with-syntax-table org-mode-transpose-word-syntax-table
  18652. (call-interactively 'transpose-words)))
  18653. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18654. (when (eq org-enable-table-editor 'optimized)
  18655. ;; If the user wants maximum table support, we need to hijack
  18656. ;; some standard editing functions
  18657. (org-remap org-mode-map
  18658. 'self-insert-command 'org-self-insert-command
  18659. 'delete-char 'org-delete-char
  18660. 'delete-backward-char 'org-delete-backward-char)
  18661. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18662. (defvar org-ctrl-c-ctrl-c-hook nil
  18663. "Hook for functions attaching themselves to `C-c C-c'.
  18664. This can be used to add additional functionality to the C-c C-c
  18665. key which executes context-dependent commands. This hook is run
  18666. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18667. run after the last test.
  18668. Each function will be called with no arguments. The function
  18669. must check if the context is appropriate for it to act. If yes,
  18670. it should do its thing and then return a non-nil value. If the
  18671. context is wrong, just do nothing and return nil.")
  18672. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18673. "Hook for functions attaching themselves to `C-c C-c'.
  18674. This can be used to add additional functionality to the C-c C-c
  18675. key which executes context-dependent commands. This hook is run
  18676. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18677. before the first test.
  18678. Each function will be called with no arguments. The function
  18679. must check if the context is appropriate for it to act. If yes,
  18680. it should do its thing and then return a non-nil value. If the
  18681. context is wrong, just do nothing and return nil.")
  18682. (defvar org-tab-first-hook nil
  18683. "Hook for functions to attach themselves to TAB.
  18684. See `org-ctrl-c-ctrl-c-hook' for more information.
  18685. This hook runs as the first action when TAB is pressed, even before
  18686. `org-cycle' messes around with the `outline-regexp' to cater for
  18687. inline tasks and plain list item folding.
  18688. If any function in this hook returns t, any other actions that
  18689. would have been caused by TAB (such as table field motion or visibility
  18690. cycling) will not occur.")
  18691. (defvar org-tab-after-check-for-table-hook nil
  18692. "Hook for functions to attach themselves to TAB.
  18693. See `org-ctrl-c-ctrl-c-hook' for more information.
  18694. This hook runs after it has been established that the cursor is not in a
  18695. table, but before checking if the cursor is in a headline or if global cycling
  18696. should be done.
  18697. If any function in this hook returns t, not other actions like visibility
  18698. cycling will be done.")
  18699. (defvar org-tab-after-check-for-cycling-hook nil
  18700. "Hook for functions to attach themselves to TAB.
  18701. See `org-ctrl-c-ctrl-c-hook' for more information.
  18702. This hook runs after it has been established that not table field motion and
  18703. not visibility should be done because of current context. This is probably
  18704. the place where a package like yasnippets can hook in.")
  18705. (defvar org-tab-before-tab-emulation-hook nil
  18706. "Hook for functions to attach themselves to TAB.
  18707. See `org-ctrl-c-ctrl-c-hook' for more information.
  18708. This hook runs after every other options for TAB have been exhausted, but
  18709. before indentation and \t insertion takes place.")
  18710. (defvar org-metaleft-hook nil
  18711. "Hook for functions attaching themselves to `M-left'.
  18712. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18713. (defvar org-metaright-hook nil
  18714. "Hook for functions attaching themselves to `M-right'.
  18715. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18716. (defvar org-metaup-hook nil
  18717. "Hook for functions attaching themselves to `M-up'.
  18718. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18719. (defvar org-metadown-hook nil
  18720. "Hook for functions attaching themselves to `M-down'.
  18721. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18722. (defvar org-shiftmetaleft-hook nil
  18723. "Hook for functions attaching themselves to `M-S-left'.
  18724. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18725. (defvar org-shiftmetaright-hook nil
  18726. "Hook for functions attaching themselves to `M-S-right'.
  18727. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18728. (defvar org-shiftmetaup-hook nil
  18729. "Hook for functions attaching themselves to `M-S-up'.
  18730. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18731. (defvar org-shiftmetadown-hook nil
  18732. "Hook for functions attaching themselves to `M-S-down'.
  18733. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18734. (defvar org-metareturn-hook nil
  18735. "Hook for functions attaching themselves to `M-RET'.
  18736. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18737. (defvar org-shiftup-hook nil
  18738. "Hook for functions attaching themselves to `S-up'.
  18739. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18740. (defvar org-shiftup-final-hook nil
  18741. "Hook for functions attaching themselves to `S-up'.
  18742. This one runs after all other options except shift-select have been excluded.
  18743. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18744. (defvar org-shiftdown-hook nil
  18745. "Hook for functions attaching themselves to `S-down'.
  18746. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18747. (defvar org-shiftdown-final-hook nil
  18748. "Hook for functions attaching themselves to `S-down'.
  18749. This one runs after all other options except shift-select have been excluded.
  18750. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18751. (defvar org-shiftleft-hook nil
  18752. "Hook for functions attaching themselves to `S-left'.
  18753. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18754. (defvar org-shiftleft-final-hook nil
  18755. "Hook for functions attaching themselves to `S-left'.
  18756. This one runs after all other options except shift-select have been excluded.
  18757. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18758. (defvar org-shiftright-hook nil
  18759. "Hook for functions attaching themselves to `S-right'.
  18760. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18761. (defvar org-shiftright-final-hook nil
  18762. "Hook for functions attaching themselves to `S-right'.
  18763. This one runs after all other options except shift-select have been excluded.
  18764. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18765. (defun org-modifier-cursor-error ()
  18766. "Throw an error, a modified cursor command was applied in wrong context."
  18767. (user-error "This command is active in special context like tables, headlines or items"))
  18768. (defun org-shiftselect-error ()
  18769. "Throw an error because Shift-Cursor command was applied in wrong context."
  18770. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18771. (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
  18772. (user-error "This command works only in special context like headlines or timestamps")))
  18773. (defun org-call-for-shift-select (cmd)
  18774. (let ((this-command-keys-shift-translated t))
  18775. (call-interactively cmd)))
  18776. (defun org-shifttab (&optional arg)
  18777. "Global visibility cycling or move to previous table field.
  18778. Call `org-table-previous-field' within a table.
  18779. When ARG is nil, cycle globally through visibility states.
  18780. When ARG is a numeric prefix, show contents of this level."
  18781. (interactive "P")
  18782. (cond
  18783. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18784. ((integerp arg)
  18785. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18786. (message "Content view to level: %d" arg)
  18787. (org-content (prefix-numeric-value arg2))
  18788. (org-cycle-show-empty-lines t)
  18789. (setq org-cycle-global-status 'overview)))
  18790. (t (call-interactively 'org-global-cycle))))
  18791. (defun org-shiftmetaleft ()
  18792. "Promote subtree or delete table column.
  18793. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18794. `org-table-delete-column', depending on context. See the
  18795. individual commands for more information."
  18796. (interactive)
  18797. (cond
  18798. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18799. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18800. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18801. ((if (not (org-region-active-p)) (org-at-item-p)
  18802. (save-excursion (goto-char (region-beginning))
  18803. (org-at-item-p)))
  18804. (call-interactively 'org-outdent-item-tree))
  18805. (t (org-modifier-cursor-error))))
  18806. (defun org-shiftmetaright ()
  18807. "Demote subtree or insert table column.
  18808. Calls `org-demote-subtree', `org-indent-item-tree', or
  18809. `org-table-insert-column', depending on context. See the
  18810. individual commands for more information."
  18811. (interactive)
  18812. (cond
  18813. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18814. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18815. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18816. ((if (not (org-region-active-p)) (org-at-item-p)
  18817. (save-excursion (goto-char (region-beginning))
  18818. (org-at-item-p)))
  18819. (call-interactively 'org-indent-item-tree))
  18820. (t (org-modifier-cursor-error))))
  18821. (defun org-shiftmetaup (&optional arg)
  18822. "Drag the line at point up.
  18823. In a table, kill the current row.
  18824. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18825. but also adjust the previous clocked item in the clock history.
  18826. Everywhere else, drag the line at point up."
  18827. (interactive "P")
  18828. (cond
  18829. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18830. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18831. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18832. (call-interactively 'org-timestamp-up)))
  18833. (t (call-interactively 'org-drag-line-backward))))
  18834. (defun org-shiftmetadown (&optional arg)
  18835. "Drag the line at point down.
  18836. In a table, insert an empty row at the current line.
  18837. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18838. but also adjust the previous clocked item in the clock history.
  18839. Everywhere else, drag the line at point down."
  18840. (interactive "P")
  18841. (cond
  18842. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18843. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18844. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18845. (call-interactively 'org-timestamp-down)))
  18846. (t (call-interactively 'org-drag-line-forward))))
  18847. (defsubst org-hidden-tree-error ()
  18848. (user-error
  18849. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18850. (defun org-metaleft (&optional arg)
  18851. "Promote heading, list item at point or move table column left.
  18852. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18853. depending on context. With no specific context, calls the Emacs
  18854. default `backward-word'. See the individual commands for more
  18855. information.
  18856. This function runs the hook `org-metaleft-hook' as a first step,
  18857. and returns at first non-nil value."
  18858. (interactive "P")
  18859. (cond
  18860. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18861. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18862. ((org-with-limited-levels
  18863. (or (org-at-heading-p)
  18864. (and (org-region-active-p)
  18865. (save-excursion
  18866. (goto-char (region-beginning))
  18867. (org-at-heading-p)))))
  18868. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18869. (call-interactively 'org-do-promote))
  18870. ;; At an inline task.
  18871. ((org-at-heading-p)
  18872. (call-interactively 'org-inlinetask-promote))
  18873. ((or (org-at-item-p)
  18874. (and (org-region-active-p)
  18875. (save-excursion
  18876. (goto-char (region-beginning))
  18877. (org-at-item-p))))
  18878. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18879. (call-interactively 'org-outdent-item))
  18880. (t (call-interactively 'backward-word))))
  18881. (defun org-metaright (&optional arg)
  18882. "Demote heading, list item at point or move table column right.
  18883. In front of a drawer or a block keyword, indent it correctly.
  18884. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18885. `org-indnet-drawer' or `org-indent-block' depending on context.
  18886. With no specific context, calls the Emacs default `forward-word'.
  18887. See the individual commands for more information.
  18888. This function runs the hook `org-metaright-hook' as a first step,
  18889. and returns at first non-nil value."
  18890. (interactive "P")
  18891. (cond
  18892. ((run-hook-with-args-until-success 'org-metaright-hook))
  18893. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18894. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18895. ((org-at-block-p) (call-interactively 'org-indent-block))
  18896. ((org-with-limited-levels
  18897. (or (org-at-heading-p)
  18898. (and (org-region-active-p)
  18899. (save-excursion
  18900. (goto-char (region-beginning))
  18901. (org-at-heading-p)))))
  18902. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18903. (call-interactively 'org-do-demote))
  18904. ;; At an inline task.
  18905. ((org-at-heading-p)
  18906. (call-interactively 'org-inlinetask-demote))
  18907. ((or (org-at-item-p)
  18908. (and (org-region-active-p)
  18909. (save-excursion
  18910. (goto-char (region-beginning))
  18911. (org-at-item-p))))
  18912. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18913. (call-interactively 'org-indent-item))
  18914. (t (call-interactively 'forward-word))))
  18915. (defun org-check-for-hidden (what)
  18916. "Check if there are hidden headlines/items in the current visual line.
  18917. WHAT can be either `headlines' or `items'. If the current line is
  18918. an outline or item heading and it has a folded subtree below it,
  18919. this function returns t, nil otherwise."
  18920. (let ((re (cond
  18921. ((eq what 'headlines) org-outline-regexp-bol)
  18922. ((eq what 'items) (org-item-beginning-re))
  18923. (t (error "This should not happen"))))
  18924. beg end)
  18925. (save-excursion
  18926. (catch 'exit
  18927. (unless (org-region-active-p)
  18928. (setq beg (point-at-bol))
  18929. (beginning-of-line 2)
  18930. (while (and (not (eobp)) ;; this is like `next-line'
  18931. (get-char-property (1- (point)) 'invisible))
  18932. (beginning-of-line 2))
  18933. (setq end (point))
  18934. (goto-char beg)
  18935. (goto-char (point-at-eol))
  18936. (setq end (max end (point)))
  18937. (while (re-search-forward re end t)
  18938. (when (get-char-property (match-beginning 0) 'invisible)
  18939. (throw 'exit t))))
  18940. nil))))
  18941. (defun org-metaup (&optional arg)
  18942. "Move subtree up or move table row up.
  18943. Calls `org-move-subtree-up' or `org-table-move-row' or
  18944. `org-move-item-up', depending on context. See the individual commands
  18945. for more information."
  18946. (interactive "P")
  18947. (cond
  18948. ((run-hook-with-args-until-success 'org-metaup-hook))
  18949. ((org-region-active-p)
  18950. (let* ((a (min (region-beginning) (region-end)))
  18951. (b (1- (max (region-beginning) (region-end))))
  18952. (c (save-excursion (goto-char a)
  18953. (move-beginning-of-line 0)))
  18954. (d (save-excursion (goto-char a)
  18955. (move-end-of-line 0) (point))))
  18956. (transpose-regions a b c d)
  18957. (goto-char c)))
  18958. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18959. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18960. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18961. (t (org-drag-element-backward))))
  18962. (defun org-metadown (&optional arg)
  18963. "Move subtree down or move table row down.
  18964. Calls `org-move-subtree-down' or `org-table-move-row' or
  18965. `org-move-item-down', depending on context. See the individual
  18966. commands for more information."
  18967. (interactive "P")
  18968. (cond
  18969. ((run-hook-with-args-until-success 'org-metadown-hook))
  18970. ((org-region-active-p)
  18971. (let* ((a (min (region-beginning) (region-end)))
  18972. (b (max (region-beginning) (region-end)))
  18973. (c (save-excursion (goto-char b)
  18974. (move-beginning-of-line 1)))
  18975. (d (save-excursion (goto-char b)
  18976. (move-end-of-line 1) (1+ (point)))))
  18977. (transpose-regions a b c d)
  18978. (goto-char d)))
  18979. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18980. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18981. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18982. (t (org-drag-element-forward))))
  18983. (defun org-shiftup (&optional arg)
  18984. "Increase item in timestamp or increase priority of current headline.
  18985. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18986. depending on context. See the individual commands for more information."
  18987. (interactive "P")
  18988. (cond
  18989. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18990. ((and org-support-shift-select (org-region-active-p))
  18991. (org-call-for-shift-select 'previous-line))
  18992. ((org-at-timestamp-p t)
  18993. (call-interactively (if org-edit-timestamp-down-means-later
  18994. 'org-timestamp-down 'org-timestamp-up)))
  18995. ((and (not (eq org-support-shift-select 'always))
  18996. org-enable-priority-commands
  18997. (org-at-heading-p))
  18998. (call-interactively 'org-priority-up))
  18999. ((and (not org-support-shift-select) (org-at-item-p))
  19000. (call-interactively 'org-previous-item))
  19001. ((org-clocktable-try-shift 'up arg))
  19002. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  19003. (org-support-shift-select
  19004. (org-call-for-shift-select 'previous-line))
  19005. (t (org-shiftselect-error))))
  19006. (defun org-shiftdown (&optional arg)
  19007. "Decrease item in timestamp or decrease priority of current headline.
  19008. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  19009. depending on context. See the individual commands for more information."
  19010. (interactive "P")
  19011. (cond
  19012. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  19013. ((and org-support-shift-select (org-region-active-p))
  19014. (org-call-for-shift-select 'next-line))
  19015. ((org-at-timestamp-p t)
  19016. (call-interactively (if org-edit-timestamp-down-means-later
  19017. 'org-timestamp-up 'org-timestamp-down)))
  19018. ((and (not (eq org-support-shift-select 'always))
  19019. org-enable-priority-commands
  19020. (org-at-heading-p))
  19021. (call-interactively 'org-priority-down))
  19022. ((and (not org-support-shift-select) (org-at-item-p))
  19023. (call-interactively 'org-next-item))
  19024. ((org-clocktable-try-shift 'down arg))
  19025. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  19026. (org-support-shift-select
  19027. (org-call-for-shift-select 'next-line))
  19028. (t (org-shiftselect-error))))
  19029. (defun org-shiftright (&optional arg)
  19030. "Cycle the thing at point or in the current line, depending on context.
  19031. Depending on context, this does one of the following:
  19032. - switch a timestamp at point one day into the future
  19033. - on a headline, switch to the next TODO keyword.
  19034. - on an item, switch entire list to the next bullet type
  19035. - on a property line, switch to the next allowed value
  19036. - on a clocktable definition line, move time block into the future"
  19037. (interactive "P")
  19038. (cond
  19039. ((run-hook-with-args-until-success 'org-shiftright-hook))
  19040. ((and org-support-shift-select (org-region-active-p))
  19041. (org-call-for-shift-select 'forward-char))
  19042. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  19043. ((and (not (eq org-support-shift-select 'always))
  19044. (org-at-heading-p))
  19045. (let ((org-inhibit-logging
  19046. (not org-treat-S-cursor-todo-selection-as-state-change))
  19047. (org-inhibit-blocking
  19048. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19049. (org-call-with-arg 'org-todo 'right)))
  19050. ((or (and org-support-shift-select
  19051. (not (eq org-support-shift-select 'always))
  19052. (org-at-item-bullet-p))
  19053. (and (not org-support-shift-select) (org-at-item-p)))
  19054. (org-call-with-arg 'org-cycle-list-bullet nil))
  19055. ((and (not (eq org-support-shift-select 'always))
  19056. (org-at-property-p))
  19057. (call-interactively 'org-property-next-allowed-value))
  19058. ((org-clocktable-try-shift 'right arg))
  19059. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19060. (org-support-shift-select
  19061. (org-call-for-shift-select 'forward-char))
  19062. (t (org-shiftselect-error))))
  19063. (defun org-shiftleft (&optional arg)
  19064. "Cycle the thing at point or in the current line, depending on context.
  19065. Depending on context, this does one of the following:
  19066. - switch a timestamp at point one day into the past
  19067. - on a headline, switch to the previous TODO keyword.
  19068. - on an item, switch entire list to the previous bullet type
  19069. - on a property line, switch to the previous allowed value
  19070. - on a clocktable definition line, move time block into the past"
  19071. (interactive "P")
  19072. (cond
  19073. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19074. ((and org-support-shift-select (org-region-active-p))
  19075. (org-call-for-shift-select 'backward-char))
  19076. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19077. ((and (not (eq org-support-shift-select 'always))
  19078. (org-at-heading-p))
  19079. (let ((org-inhibit-logging
  19080. (not org-treat-S-cursor-todo-selection-as-state-change))
  19081. (org-inhibit-blocking
  19082. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19083. (org-call-with-arg 'org-todo 'left)))
  19084. ((or (and org-support-shift-select
  19085. (not (eq org-support-shift-select 'always))
  19086. (org-at-item-bullet-p))
  19087. (and (not org-support-shift-select) (org-at-item-p)))
  19088. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19089. ((and (not (eq org-support-shift-select 'always))
  19090. (org-at-property-p))
  19091. (call-interactively 'org-property-previous-allowed-value))
  19092. ((org-clocktable-try-shift 'left arg))
  19093. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19094. (org-support-shift-select
  19095. (org-call-for-shift-select 'backward-char))
  19096. (t (org-shiftselect-error))))
  19097. (defun org-shiftcontrolright ()
  19098. "Switch to next TODO set."
  19099. (interactive)
  19100. (cond
  19101. ((and org-support-shift-select (org-region-active-p))
  19102. (org-call-for-shift-select 'forward-word))
  19103. ((and (not (eq org-support-shift-select 'always))
  19104. (org-at-heading-p))
  19105. (org-call-with-arg 'org-todo 'nextset))
  19106. (org-support-shift-select
  19107. (org-call-for-shift-select 'forward-word))
  19108. (t (org-shiftselect-error))))
  19109. (defun org-shiftcontrolleft ()
  19110. "Switch to previous TODO set."
  19111. (interactive)
  19112. (cond
  19113. ((and org-support-shift-select (org-region-active-p))
  19114. (org-call-for-shift-select 'backward-word))
  19115. ((and (not (eq org-support-shift-select 'always))
  19116. (org-at-heading-p))
  19117. (org-call-with-arg 'org-todo 'previousset))
  19118. (org-support-shift-select
  19119. (org-call-for-shift-select 'backward-word))
  19120. (t (org-shiftselect-error))))
  19121. (defun org-shiftcontrolup (&optional n)
  19122. "Change timestamps synchronously up in CLOCK log lines.
  19123. Optional argument N tells to change by that many units."
  19124. (interactive "P")
  19125. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19126. (let (org-support-shift-select)
  19127. (org-clock-timestamps-up n))
  19128. (user-error "Not at a clock log")))
  19129. (defun org-shiftcontroldown (&optional n)
  19130. "Change timestamps synchronously down in CLOCK log lines.
  19131. Optional argument N tells to change by that many units."
  19132. (interactive "P")
  19133. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19134. (let (org-support-shift-select)
  19135. (org-clock-timestamps-down n))
  19136. (user-error "Not at a clock log")))
  19137. (defun org-increase-number-at-point (&optional inc)
  19138. "Increment the number at point.
  19139. With an optional prefix numeric argument INC, increment using
  19140. this numeric value."
  19141. (interactive "p")
  19142. (if (not (number-at-point))
  19143. (user-error "Not on a number")
  19144. (unless inc (setq inc 1))
  19145. (let ((pos (point))
  19146. (beg (skip-chars-backward "-+^/*0-9eE."))
  19147. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19148. (setq nap (buffer-substring-no-properties
  19149. (+ pos beg) (+ pos beg end)))
  19150. (delete-region (+ pos beg) (+ pos beg end))
  19151. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19152. (when (org-at-table-p)
  19153. (org-table-align)
  19154. (org-table-end-of-field 1))))
  19155. (defun org-decrease-number-at-point (&optional inc)
  19156. "Decrement the number at point.
  19157. With an optional prefix numeric argument INC, decrement using
  19158. this numeric value."
  19159. (interactive "p")
  19160. (org-increase-number-at-point (- (or inc 1))))
  19161. (defun org-ctrl-c-ret ()
  19162. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19163. (interactive)
  19164. (cond
  19165. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19166. (t (call-interactively 'org-insert-heading))))
  19167. (defun org-find-visible ()
  19168. (let ((s (point)))
  19169. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19170. (get-char-property s 'invisible)))
  19171. s))
  19172. (defun org-find-invisible ()
  19173. (let ((s (point)))
  19174. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19175. (not (get-char-property s 'invisible))))
  19176. s))
  19177. (defun org-copy-visible (beg end)
  19178. "Copy the visible parts of the region."
  19179. (interactive "r")
  19180. (let (snippets s)
  19181. (save-excursion
  19182. (save-restriction
  19183. (narrow-to-region beg end)
  19184. (setq s (goto-char (point-min)))
  19185. (while (not (= (point) (point-max)))
  19186. (goto-char (org-find-invisible))
  19187. (push (buffer-substring s (point)) snippets)
  19188. (setq s (goto-char (org-find-visible))))))
  19189. (kill-new (apply 'concat (nreverse snippets)))))
  19190. (defun org-copy-special ()
  19191. "Copy region in table or copy current subtree.
  19192. Calls `org-table-copy' or `org-copy-subtree', depending on context.
  19193. See the individual commands for more information."
  19194. (interactive)
  19195. (call-interactively
  19196. (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
  19197. (defun org-cut-special ()
  19198. "Cut region in table or cut current subtree.
  19199. Calls `org-table-copy' or `org-cut-subtree', depending on context.
  19200. See the individual commands for more information."
  19201. (interactive)
  19202. (call-interactively
  19203. (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
  19204. (defun org-paste-special (arg)
  19205. "Paste rectangular region into table, or past subtree relative to level.
  19206. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19207. See the individual commands for more information."
  19208. (interactive "P")
  19209. (if (org-at-table-p)
  19210. (org-table-paste-rectangle)
  19211. (org-paste-subtree arg)))
  19212. (defsubst org-in-fixed-width-region-p ()
  19213. "Is point in a fixed-width region?"
  19214. (save-match-data
  19215. (eq 'fixed-width (org-element-type (org-element-at-point)))))
  19216. (defun org-edit-special (&optional arg)
  19217. "Call a special editor for the element at point.
  19218. When at a table, call the formula editor with `org-table-edit-formulas'.
  19219. When in a source code block, call `org-edit-src-code'.
  19220. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19221. When in an export block, call `org-edit-export-block'.
  19222. When at an #+INCLUDE keyword, visit the included file.
  19223. When at a footnote reference, call `org-edit-footnote-reference'
  19224. On a link, call `ffap' to visit the link at point.
  19225. Otherwise, return a user error."
  19226. (interactive "P")
  19227. (let ((element (org-element-at-point)))
  19228. (assert (not buffer-read-only) nil
  19229. "Buffer is read-only: %s" (buffer-name))
  19230. (case (org-element-type element)
  19231. (src-block
  19232. (if (not arg) (org-edit-src-code)
  19233. (let* ((info (org-babel-get-src-block-info))
  19234. (lang (nth 0 info))
  19235. (params (nth 2 info))
  19236. (session (cdr (assq :session params))))
  19237. (if (not session) (org-edit-src-code)
  19238. ;; At a src-block with a session and function called with
  19239. ;; an ARG: switch to the buffer related to the inferior
  19240. ;; process.
  19241. (switch-to-buffer
  19242. (funcall (intern (concat "org-babel-prep-session:" lang))
  19243. session params))))))
  19244. (keyword
  19245. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19246. (org-open-link-from-string
  19247. (format "[[%s]]"
  19248. (expand-file-name
  19249. (let ((value (org-element-property :value element)))
  19250. (cond ((not (org-string-nw-p value))
  19251. (user-error "No file to edit"))
  19252. ((string-match "\\`\"\\(.*?\\)\"" value)
  19253. (match-string 1 value))
  19254. ((string-match "\\`[^ \t\"]\\S-*" value)
  19255. (match-string 0 value))
  19256. (t (user-error "No valid file specified")))))))
  19257. (user-error "No special environment to edit here")))
  19258. (table
  19259. (if (eq (org-element-property :type element) 'table.el)
  19260. (org-edit-table.el)
  19261. (call-interactively 'org-table-edit-formulas)))
  19262. ;; Only Org tables contain `table-row' type elements.
  19263. (table-row (call-interactively 'org-table-edit-formulas))
  19264. (example-block (org-edit-src-code))
  19265. (export-block (org-edit-export-block))
  19266. (fixed-width (org-edit-fixed-width-region))
  19267. (otherwise
  19268. ;; No notable element at point. Though, we may be at a link or
  19269. ;; a footnote reference, which are objects. Thus, scan deeper.
  19270. (let ((context (org-element-context element)))
  19271. (case (org-element-type context)
  19272. (link (call-interactively #'ffap))
  19273. (footnote-reference (org-edit-footnote-reference))
  19274. (t (user-error "No special environment to edit here"))))))))
  19275. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19276. (defun org-ctrl-c-ctrl-c (&optional arg)
  19277. "Set tags in headline, or update according to changed information at point.
  19278. This command does many different things, depending on context:
  19279. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19280. this is what we do.
  19281. - If the cursor is on a statistics cookie, update it.
  19282. - If the cursor is in a headline, prompt for tags and insert them
  19283. into the current line, aligned to `org-tags-column'. When called
  19284. with prefix arg, realign all tags in the current buffer.
  19285. - If the cursor is in one of the special #+KEYWORD lines, this
  19286. triggers scanning the buffer for these lines and updating the
  19287. information.
  19288. - If the cursor is inside a table, realign the table. This command
  19289. works even if the automatic table editor has been turned off.
  19290. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19291. the entire table.
  19292. - If the cursor is at a footnote reference or definition, jump to
  19293. the corresponding definition or references, respectively.
  19294. - If the cursor is a the beginning of a dynamic block, update it.
  19295. - If the current buffer is a capture buffer, close note and file it.
  19296. - If the cursor is on a <<<target>>>, update radio targets and
  19297. corresponding links in this buffer.
  19298. - If the cursor is on a numbered item in a plain list, renumber the
  19299. ordered list.
  19300. - If the cursor is on a checkbox, toggle it.
  19301. - If the cursor is on a code block, evaluate it. The variable
  19302. `org-confirm-babel-evaluate' can be used to control prompting
  19303. before code block evaluation, by default every code block
  19304. evaluation requires confirmation. Code block evaluation can be
  19305. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19306. (interactive "P")
  19307. (cond
  19308. ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
  19309. org-occur-highlights)
  19310. (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19311. (org-remove-occur-highlights)
  19312. (message "Temporary highlights/overlays removed from current buffer"))
  19313. ((and (local-variable-p 'org-finish-function (current-buffer))
  19314. (fboundp org-finish-function))
  19315. (funcall org-finish-function))
  19316. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19317. (t
  19318. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  19319. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19320. (user-error "C-c C-c can do nothing useful at this location"))
  19321. (let* ((context (org-element-context))
  19322. (type (org-element-type context)))
  19323. (case type
  19324. ;; When at a link, act according to the parent instead.
  19325. (link (setq context (org-element-property :parent context))
  19326. (setq type (org-element-type context)))
  19327. ;; Unsupported object types: refer to the first supported
  19328. ;; element or object containing it.
  19329. ((bold code entity export-snippet inline-babel-call inline-src-block
  19330. italic latex-fragment line-break macro strike-through subscript
  19331. superscript underline verbatim)
  19332. (setq context
  19333. (org-element-lineage
  19334. context '(radio-target paragraph verse-block table-cell)))))
  19335. ;; For convenience: at the first line of a paragraph on the
  19336. ;; same line as an item, apply function on that item instead.
  19337. (when (eq type 'paragraph)
  19338. (let ((parent (org-element-property :parent context)))
  19339. (when (and (eq (org-element-type parent) 'item)
  19340. (= (line-beginning-position)
  19341. (org-element-property :begin parent)))
  19342. (setq context parent type 'item))))
  19343. ;; Act according to type of element or object at point.
  19344. (case type
  19345. (clock (org-clock-update-time-maybe))
  19346. (dynamic-block
  19347. (save-excursion
  19348. (goto-char (org-element-property :post-affiliated context))
  19349. (org-update-dblock)))
  19350. (footnote-definition
  19351. (goto-char (org-element-property :post-affiliated context))
  19352. (call-interactively 'org-footnote-action))
  19353. (footnote-reference (call-interactively 'org-footnote-action))
  19354. ((headline inlinetask)
  19355. (save-excursion (goto-char (org-element-property :begin context))
  19356. (call-interactively 'org-set-tags)))
  19357. (item
  19358. ;; At an item: a double C-u set checkbox to "[-]"
  19359. ;; unconditionally, whereas a single one will toggle its
  19360. ;; presence. Without a universal argument, if the item
  19361. ;; has a checkbox, toggle it. Otherwise repair the list.
  19362. (let* ((box (org-element-property :checkbox context))
  19363. (struct (org-element-property :structure context))
  19364. (old-struct (copy-tree struct))
  19365. (parents (org-list-parents-alist struct))
  19366. (prevs (org-list-prevs-alist struct))
  19367. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19368. (org-list-set-checkbox
  19369. (org-element-property :begin context) struct
  19370. (cond ((equal arg '(16)) "[-]")
  19371. ((and (not box) (equal arg '(4))) "[ ]")
  19372. ((or (not box) (equal arg '(4))) nil)
  19373. ((eq box 'on) "[ ]")
  19374. (t "[X]")))
  19375. ;; Mimic `org-list-write-struct' but with grabbing
  19376. ;; a return value from `org-list-struct-fix-box'.
  19377. (org-list-struct-fix-ind struct parents 2)
  19378. (org-list-struct-fix-item-end struct)
  19379. (org-list-struct-fix-bul struct prevs)
  19380. (org-list-struct-fix-ind struct parents)
  19381. (let ((block-item
  19382. (org-list-struct-fix-box struct parents prevs orderedp)))
  19383. (if (and box (equal struct old-struct))
  19384. (if (equal arg '(16))
  19385. (message "Checkboxes already reset")
  19386. (user-error "Cannot toggle this checkbox: %s"
  19387. (if (eq box 'on)
  19388. "all subitems checked"
  19389. "unchecked subitems")))
  19390. (org-list-struct-apply-struct struct old-struct)
  19391. (org-update-checkbox-count-maybe))
  19392. (when block-item
  19393. (message "Checkboxes were removed due to empty box at line %d"
  19394. (org-current-line block-item))))))
  19395. (keyword
  19396. (let ((org-inhibit-startup-visibility-stuff t)
  19397. (org-startup-align-all-tables nil))
  19398. (when (boundp 'org-table-coordinate-overlays)
  19399. (mapc 'delete-overlay org-table-coordinate-overlays)
  19400. (setq org-table-coordinate-overlays nil))
  19401. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19402. (message "Local setup has been refreshed"))
  19403. (plain-list
  19404. ;; At a plain list, with a double C-u argument, set
  19405. ;; checkboxes of each item to "[-]", whereas a single one
  19406. ;; will toggle their presence according to the state of the
  19407. ;; first item in the list. Without an argument, repair the
  19408. ;; list.
  19409. (let* ((begin (org-element-property :contents-begin context))
  19410. (beginm (move-marker (make-marker) begin))
  19411. (struct (org-element-property :structure context))
  19412. (old-struct (copy-tree struct))
  19413. (first-box (save-excursion
  19414. (goto-char begin)
  19415. (looking-at org-list-full-item-re)
  19416. (match-string-no-properties 3)))
  19417. (new-box (cond ((equal arg '(16)) "[-]")
  19418. ((equal arg '(4)) (unless first-box "[ ]"))
  19419. ((equal first-box "[X]") "[ ]")
  19420. (t "[X]"))))
  19421. (cond
  19422. (arg
  19423. (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
  19424. (org-list-get-all-items
  19425. begin struct (org-list-prevs-alist struct))))
  19426. ((and first-box (eq (point) begin))
  19427. ;; For convenience, when point is at bol on the first
  19428. ;; item of the list and no argument is provided, simply
  19429. ;; toggle checkbox of that item, if any.
  19430. (org-list-set-checkbox begin struct new-box)))
  19431. (org-list-write-struct
  19432. struct (org-list-parents-alist struct) old-struct)
  19433. (org-update-checkbox-count-maybe)
  19434. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19435. ((property-drawer node-property)
  19436. (call-interactively 'org-property-action))
  19437. ((radio-target target)
  19438. (call-interactively 'org-update-radio-target-regexp))
  19439. (statistics-cookie
  19440. (call-interactively 'org-update-statistics-cookies))
  19441. ((table table-cell table-row)
  19442. ;; At a table, recalculate every field and align it. Also
  19443. ;; send the table if necessary. If the table has
  19444. ;; a `table.el' type, just give up. At a table row or
  19445. ;; cell, maybe recalculate line but always align table.
  19446. (if (eq (org-element-property :type context) 'table.el)
  19447. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19448. Use \\[org-edit-special] to edit table.el tables"))
  19449. (let ((org-enable-table-editor t))
  19450. (if (or (eq type 'table)
  19451. ;; Check if point is at a TBLFM line.
  19452. (and (eq type 'table-row)
  19453. (= (point) (org-element-property :end context))))
  19454. (save-excursion
  19455. (if (org-at-TBLFM-p)
  19456. (progn (require 'org-table)
  19457. (org-table-calc-current-TBLFM))
  19458. (goto-char (org-element-property :contents-begin context))
  19459. (org-call-with-arg 'org-table-recalculate (or arg t))
  19460. (orgtbl-send-table 'maybe)))
  19461. (org-table-maybe-eval-formula)
  19462. (cond (arg (call-interactively 'org-table-recalculate))
  19463. ((org-table-maybe-recalculate-line))
  19464. (t (org-table-align)))))))
  19465. (timestamp (org-timestamp-change 0 'day))
  19466. (otherwise
  19467. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19468. (user-error
  19469. "C-c C-c can do nothing useful at this location")))))))))
  19470. (defun org-mode-restart ()
  19471. (interactive)
  19472. (let ((indent-status (org-bound-and-true-p org-indent-mode)))
  19473. (funcall major-mode)
  19474. (hack-local-variables)
  19475. (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
  19476. (org-indent-mode -1)))
  19477. (message "%s restarted" major-mode))
  19478. (defun org-kill-note-or-show-branches ()
  19479. "If this is a Note buffer, abort storing the note. Else call `show-branches'."
  19480. (interactive)
  19481. (if (not org-finish-function)
  19482. (progn
  19483. (outline-hide-subtree)
  19484. (call-interactively 'outline-show-branches))
  19485. (let ((org-note-abort t))
  19486. (funcall org-finish-function))))
  19487. (defun org-delete-indentation (&optional ARG)
  19488. "Join current line to previous and fix whitespace at join.
  19489. If previous line is a headline add to headline title. Otherwise
  19490. the function calls `delete-indentation'.
  19491. With argument, join this line to following line."
  19492. (interactive "*P")
  19493. (if (save-excursion
  19494. (if ARG (beginning-of-line)
  19495. (forward-line -1))
  19496. (looking-at org-complex-heading-regexp))
  19497. ;; At headline.
  19498. (let ((tags-column (when (match-beginning 5)
  19499. (save-excursion (goto-char (match-beginning 5))
  19500. (current-column))))
  19501. (string (concat " " (progn (when ARG (forward-line 1))
  19502. (org-trim (delete-and-extract-region
  19503. (line-beginning-position)
  19504. (line-end-position)))))))
  19505. (unless (bobp) (delete-region (point) (1- (point))))
  19506. (goto-char (or (match-end 4)
  19507. (match-beginning 5)
  19508. (match-end 0)))
  19509. (skip-chars-backward " \t")
  19510. (save-excursion (insert string))
  19511. ;; Adjust alignment of tags.
  19512. (when tags-column
  19513. (org-align-tags-here (if org-auto-align-tags
  19514. org-tags-column
  19515. tags-column))))
  19516. (delete-indentation ARG)))
  19517. (defun org-open-line (n)
  19518. "Insert a new row in tables, call `open-line' elsewhere.
  19519. If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
  19520. (interactive "*p")
  19521. (cond
  19522. ((not org-special-ctrl-o)
  19523. (open-line n))
  19524. ((org-at-table-p)
  19525. (org-table-insert-row))
  19526. (t
  19527. (open-line n))))
  19528. (defun org-return (&optional indent)
  19529. "Goto next table row or insert a newline.
  19530. Calls `org-table-next-row' or `newline', depending on context.
  19531. When optional INDENT argument is non-nil, call
  19532. `newline-and-indent' instead of `newline'.
  19533. When `org-return-follows-link' is non-nil and point is on
  19534. a timestamp or a link, call `org-open-at-point'. However, it
  19535. will not happen if point is in a table or on a \"dead\"
  19536. object (e.g., within a comment). In these case, you need to use
  19537. `org-open-at-point' directly."
  19538. (interactive)
  19539. (let ((context (if org-return-follows-link (org-element-context)
  19540. (org-element-at-point))))
  19541. (cond
  19542. ;; In a table, call `org-table-next-row'.
  19543. ((or (and (eq (org-element-type context) 'table)
  19544. (>= (point) (org-element-property :contents-begin context))
  19545. (< (point) (org-element-property :contents-end context)))
  19546. (org-element-lineage context '(table-row table-cell) t))
  19547. (org-table-justify-field-maybe)
  19548. (call-interactively #'org-table-next-row))
  19549. ;; On a link or a timestamp, call `org-open-at-point' if
  19550. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19551. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19552. ((and org-return-follows-link
  19553. (or (org-in-regexp org-ts-regexp-both nil t)
  19554. (org-in-regexp org-tsr-regexp-both nil t)
  19555. (org-in-regexp org-any-link-re nil t)))
  19556. (call-interactively #'org-open-at-point))
  19557. ;; Insert newline in heading, but preserve tags.
  19558. ((and (not (bolp))
  19559. (save-excursion (beginning-of-line)
  19560. (looking-at org-complex-heading-regexp)))
  19561. ;; At headline. Split line. However, if point is on keyword,
  19562. ;; priority cookie or tags, do not break any of them: add
  19563. ;; a newline after the headline instead.
  19564. (let ((tags-column (and (match-beginning 5)
  19565. (save-excursion (goto-char (match-beginning 5))
  19566. (current-column))))
  19567. (string
  19568. (when (and (match-end 4)
  19569. (>= (point)
  19570. (or (match-end 3) (match-end 2) (1+ (match-end 1))))
  19571. (<= (point) (match-end 4)))
  19572. (delete-and-extract-region (point) (match-end 4)))))
  19573. (when (and tags-column string) ; Adjust tag alignment.
  19574. (org-align-tags-here
  19575. (if org-auto-align-tags org-tags-column tags-column)))
  19576. (end-of-line)
  19577. (org-show-entry)
  19578. (if indent (newline-and-indent) (newline))
  19579. (when string (save-excursion (insert (org-trim string))))))
  19580. ;; In a list, make sure indenting keeps trailing text within.
  19581. ((and indent
  19582. (not (eolp))
  19583. (org-element-lineage context '(item)))
  19584. (let ((trailing-data
  19585. (delete-and-extract-region (point) (line-end-position))))
  19586. (newline-and-indent)
  19587. (save-excursion (insert trailing-data))))
  19588. (t (if indent (newline-and-indent) (newline))))))
  19589. (defun org-return-indent ()
  19590. "Goto next table row or insert a newline and indent.
  19591. Calls `org-table-next-row' or `newline-and-indent', depending on
  19592. context. See the individual commands for more information."
  19593. (interactive)
  19594. (org-return t))
  19595. (defun org-ctrl-c-star ()
  19596. "Compute table, or change heading status of lines.
  19597. Calls `org-table-recalculate' or `org-toggle-heading',
  19598. depending on context."
  19599. (interactive)
  19600. (cond
  19601. ((org-at-table-p)
  19602. (call-interactively 'org-table-recalculate))
  19603. (t
  19604. ;; Convert all lines in region to list items
  19605. (call-interactively 'org-toggle-heading))))
  19606. (defun org-ctrl-c-minus ()
  19607. "Insert separator line in table or modify bullet status of line.
  19608. Also turns a plain line or a region of lines into list items.
  19609. Calls `org-table-insert-hline', `org-toggle-item', or
  19610. `org-cycle-list-bullet', depending on context."
  19611. (interactive)
  19612. (cond
  19613. ((org-at-table-p)
  19614. (call-interactively 'org-table-insert-hline))
  19615. ((org-region-active-p)
  19616. (call-interactively 'org-toggle-item))
  19617. ((org-in-item-p)
  19618. (call-interactively 'org-cycle-list-bullet))
  19619. (t
  19620. (call-interactively 'org-toggle-item))))
  19621. (defun org-toggle-item (arg)
  19622. "Convert headings or normal lines to items, items to normal lines.
  19623. If there is no active region, only the current line is considered.
  19624. If the first non blank line in the region is a headline, convert
  19625. all headlines to items, shifting text accordingly.
  19626. If it is an item, convert all items to normal lines.
  19627. If it is normal text, change region into a list of items.
  19628. With a prefix argument ARG, change the region in a single item."
  19629. (interactive "P")
  19630. (let ((shift-text
  19631. (function
  19632. ;; Shift text in current section to IND, from point to END.
  19633. ;; The function leaves point to END line.
  19634. (lambda (ind end)
  19635. (let ((min-i 1000) (end (copy-marker end)))
  19636. ;; First determine the minimum indentation (MIN-I) of
  19637. ;; the text.
  19638. (save-excursion
  19639. (catch 'exit
  19640. (while (< (point) end)
  19641. (let ((i (org-get-indentation)))
  19642. (cond
  19643. ;; Skip blank lines and inline tasks.
  19644. ((looking-at "^[ \t]*$"))
  19645. ((looking-at org-outline-regexp-bol))
  19646. ;; We can't find less than 0 indentation.
  19647. ((zerop i) (throw 'exit (setq min-i 0)))
  19648. ((< i min-i) (setq min-i i))))
  19649. (forward-line))))
  19650. ;; Then indent each line so that a line indented to
  19651. ;; MIN-I becomes indented to IND. Ignore blank lines
  19652. ;; and inline tasks in the process.
  19653. (let ((delta (- ind min-i)))
  19654. (while (< (point) end)
  19655. (unless (or (looking-at "^[ \t]*$")
  19656. (looking-at org-outline-regexp-bol))
  19657. (org-indent-line-to (+ (org-get-indentation) delta)))
  19658. (forward-line)))))))
  19659. (skip-blanks
  19660. (function
  19661. ;; Return beginning of first non-blank line, starting from
  19662. ;; line at POS.
  19663. (lambda (pos)
  19664. (save-excursion
  19665. (goto-char pos)
  19666. (skip-chars-forward " \r\t\n")
  19667. (point-at-bol)))))
  19668. beg end)
  19669. ;; Determine boundaries of changes.
  19670. (if (org-region-active-p)
  19671. (setq beg (funcall skip-blanks (region-beginning))
  19672. end (copy-marker (region-end)))
  19673. (setq beg (funcall skip-blanks (point-at-bol))
  19674. end (copy-marker (point-at-eol))))
  19675. ;; Depending on the starting line, choose an action on the text
  19676. ;; between BEG and END.
  19677. (org-with-limited-levels
  19678. (save-excursion
  19679. (goto-char beg)
  19680. (cond
  19681. ;; Case 1. Start at an item: de-itemize. Note that it only
  19682. ;; happens when a region is active: `org-ctrl-c-minus'
  19683. ;; would call `org-cycle-list-bullet' otherwise.
  19684. ((org-at-item-p)
  19685. (while (< (point) end)
  19686. (when (org-at-item-p)
  19687. (skip-chars-forward " \t")
  19688. (delete-region (point) (match-end 0)))
  19689. (forward-line)))
  19690. ;; Case 2. Start at an heading: convert to items.
  19691. ((org-at-heading-p)
  19692. (let* ((bul (org-list-bullet-string "-"))
  19693. (bul-len (length bul))
  19694. (done (org-entry-is-done-p))
  19695. (todo (org-entry-is-todo-p))
  19696. ;; Indentation of the first heading. It should be
  19697. ;; relative to the indentation of its parent, if any.
  19698. (start-ind (save-excursion
  19699. (cond
  19700. ((not org-adapt-indentation) 0)
  19701. ((not (outline-previous-heading)) 0)
  19702. (t (length (match-string 0))))))
  19703. ;; Level of first heading. Further headings will be
  19704. ;; compared to it to determine hierarchy in the list.
  19705. (ref-level (org-reduced-level (org-outline-level))))
  19706. (when (or done todo) (org-todo ""))
  19707. (while (< (point) end)
  19708. (let* ((level (org-reduced-level (org-outline-level)))
  19709. (delta (max 0 (- level ref-level))))
  19710. ;; If current headline is less indented than the first
  19711. ;; one, set it as reference, in order to preserve
  19712. ;; subtrees.
  19713. (when (< level ref-level) (setq ref-level level))
  19714. (replace-match bul t t)
  19715. (org-indent-line-to (+ start-ind (* delta bul-len)))
  19716. (when (or done todo)
  19717. (let* ((struct (org-list-struct))
  19718. (old (copy-tree struct)))
  19719. (org-list-set-checkbox (line-beginning-position)
  19720. struct
  19721. (if done "[X]" "[ ]"))
  19722. (org-list-write-struct struct
  19723. (org-list-parents-alist struct)
  19724. old)))
  19725. ;; Ensure all text down to END (or SECTION-END) belongs
  19726. ;; to the newly created item.
  19727. (let ((section-end (save-excursion
  19728. (or (outline-next-heading) (point)))))
  19729. (forward-line)
  19730. (funcall shift-text
  19731. (+ start-ind (* (1+ delta) bul-len))
  19732. (min end section-end)))))))
  19733. ;; Case 3. Normal line with ARG: make the first line of region
  19734. ;; an item, and shift indentation of others lines to
  19735. ;; set them as item's body.
  19736. (arg (let* ((bul (org-list-bullet-string "-"))
  19737. (bul-len (length bul))
  19738. (ref-ind (org-get-indentation)))
  19739. (skip-chars-forward " \t")
  19740. (insert bul)
  19741. (forward-line)
  19742. (while (< (point) end)
  19743. ;; Ensure that lines less indented than first one
  19744. ;; still get included in item body.
  19745. (funcall shift-text
  19746. (+ ref-ind bul-len)
  19747. (min end (save-excursion (or (outline-next-heading)
  19748. (point)))))
  19749. (forward-line))))
  19750. ;; Case 4. Normal line without ARG: turn each non-item line
  19751. ;; into an item.
  19752. (t
  19753. (while (< (point) end)
  19754. (unless (or (org-at-heading-p) (org-at-item-p))
  19755. (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
  19756. (replace-match
  19757. (concat "\\1" (org-list-bullet-string "-") "\\2"))))
  19758. (forward-line))))))))
  19759. (defun org-toggle-heading (&optional nstars)
  19760. "Convert headings to normal text, or items or text to headings.
  19761. If there is no active region, only convert the current line.
  19762. With a \\[universal-argument] prefix, convert the whole list at
  19763. point into heading.
  19764. In a region:
  19765. - If the first non blank line is a headline, remove the stars
  19766. from all headlines in the region.
  19767. - If it is a normal line, turn each and every normal line (i.e.,
  19768. not an heading or an item) in the region into headings. If you
  19769. want to convert only the first line of this region, use one
  19770. universal prefix argument.
  19771. - If it is a plain list item, turn all plain list items into headings.
  19772. When converting a line into a heading, the number of stars is chosen
  19773. such that the lines become children of the current entry. However,
  19774. when a numeric prefix argument is given, its value determines the
  19775. number of stars to add."
  19776. (interactive "P")
  19777. (let ((skip-blanks
  19778. (function
  19779. ;; Return beginning of first non-blank line, starting from
  19780. ;; line at POS.
  19781. (lambda (pos)
  19782. (save-excursion
  19783. (goto-char pos)
  19784. (while (org-at-comment-p) (forward-line))
  19785. (skip-chars-forward " \r\t\n")
  19786. (point-at-bol)))))
  19787. beg end toggled)
  19788. ;; Determine boundaries of changes. If a universal prefix has
  19789. ;; been given, put the list in a region. If region ends at a bol,
  19790. ;; do not consider the last line to be in the region.
  19791. (when (and current-prefix-arg (org-at-item-p))
  19792. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19793. (org-mark-element))
  19794. (if (org-region-active-p)
  19795. (setq beg (funcall skip-blanks (region-beginning))
  19796. end (copy-marker (save-excursion
  19797. (goto-char (region-end))
  19798. (if (bolp) (point) (point-at-eol)))))
  19799. (setq beg (funcall skip-blanks (point-at-bol))
  19800. end (copy-marker (point-at-eol))))
  19801. ;; Ensure inline tasks don't count as headings.
  19802. (org-with-limited-levels
  19803. (save-excursion
  19804. (goto-char beg)
  19805. (cond
  19806. ;; Case 1. Started at an heading: de-star headings.
  19807. ((org-at-heading-p)
  19808. (while (< (point) end)
  19809. (when (org-at-heading-p t)
  19810. (looking-at org-outline-regexp) (replace-match "")
  19811. (setq toggled t))
  19812. (forward-line)))
  19813. ;; Case 2. Started at an item: change items into headlines.
  19814. ;; One star will be added by `org-list-to-subtree'.
  19815. ((org-at-item-p)
  19816. (while (< (point) end)
  19817. (when (org-at-item-p)
  19818. ;; Pay attention to cases when region ends before list.
  19819. (let* ((struct (org-list-struct))
  19820. (list-end (min (org-list-get-bottom-point struct) (1+ end))))
  19821. (save-restriction
  19822. (narrow-to-region (point) list-end)
  19823. (insert (org-list-to-subtree (org-list-parse-list t)))))
  19824. (setq toggled t))
  19825. (forward-line)))
  19826. ;; Case 3. Started at normal text: make every line an heading,
  19827. ;; skipping headlines and items.
  19828. (t (let* ((stars
  19829. (make-string
  19830. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19831. (add-stars
  19832. (cond (nstars "") ; stars from prefix only
  19833. ((equal stars "") "*") ; before first heading
  19834. (org-odd-levels-only "**") ; inside heading, odd
  19835. (t "*"))) ; inside heading, oddeven
  19836. (rpl (concat stars add-stars " "))
  19837. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19838. (while (< (point) (if (equal nstars '(4)) lend end))
  19839. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19840. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19841. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19842. (forward-line)))))))
  19843. (unless toggled (message "Cannot toggle heading from here"))))
  19844. (defun org-meta-return (&optional _arg)
  19845. "Insert a new heading or wrap a region in a table.
  19846. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19847. on context. See the individual commands for more information."
  19848. (interactive)
  19849. (org-check-before-invisible-edit 'insert)
  19850. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19851. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19852. #'org-insert-heading))))
  19853. ;;; Menu entries
  19854. (defsubst org-in-subtree-not-table-p ()
  19855. "Are we in a subtree and not in a table?"
  19856. (and (not (org-before-first-heading-p))
  19857. (not (org-at-table-p))))
  19858. ;; Define the Org-mode menus
  19859. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19860. '("Tbl"
  19861. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19862. ["Next Field" org-cycle (org-at-table-p)]
  19863. ["Previous Field" org-shifttab (org-at-table-p)]
  19864. ["Next Row" org-return (org-at-table-p)]
  19865. "--"
  19866. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19867. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19868. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19869. "--"
  19870. ("Column"
  19871. ["Move Column Left" org-metaleft (org-at-table-p)]
  19872. ["Move Column Right" org-metaright (org-at-table-p)]
  19873. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19874. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19875. ("Row"
  19876. ["Move Row Up" org-metaup (org-at-table-p)]
  19877. ["Move Row Down" org-metadown (org-at-table-p)]
  19878. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19879. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19880. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19881. "--"
  19882. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19883. ("Rectangle"
  19884. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19885. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19886. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19887. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19888. "--"
  19889. ("Calculate"
  19890. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19891. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19892. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19893. "--"
  19894. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19895. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19896. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19897. "--"
  19898. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19899. "--"
  19900. ["Sum Column/Rectangle" org-table-sum
  19901. (or (org-at-table-p) (org-region-active-p))]
  19902. ["Which Column?" org-table-current-column (org-at-table-p)])
  19903. ["Debug Formulas"
  19904. org-table-toggle-formula-debugger
  19905. :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
  19906. ["Show Col/Row Numbers"
  19907. org-table-toggle-coordinate-overlays
  19908. :style toggle
  19909. :selected (org-bound-and-true-p org-table-overlay-coordinates)]
  19910. "--"
  19911. ["Create" org-table-create (and (not (org-at-table-p))
  19912. org-enable-table-editor)]
  19913. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19914. ["Import from File" org-table-import (not (org-at-table-p))]
  19915. ["Export to File" org-table-export (org-at-table-p)]
  19916. "--"
  19917. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19918. "--"
  19919. ("Plot"
  19920. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19921. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19922. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19923. '("Org"
  19924. ("Show/Hide"
  19925. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19926. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19927. ["Sparse Tree..." org-sparse-tree t]
  19928. ["Reveal Context" org-reveal t]
  19929. ["Show All" outline-show-all t]
  19930. "--"
  19931. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19932. "--"
  19933. ["New Heading" org-insert-heading t]
  19934. ("Navigate Headings"
  19935. ["Up" outline-up-heading t]
  19936. ["Next" outline-next-visible-heading t]
  19937. ["Previous" outline-previous-visible-heading t]
  19938. ["Next Same Level" outline-forward-same-level t]
  19939. ["Previous Same Level" outline-backward-same-level t]
  19940. "--"
  19941. ["Jump" org-goto t])
  19942. ("Edit Structure"
  19943. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19944. "--"
  19945. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19946. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19947. "--"
  19948. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19949. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19950. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19951. "--"
  19952. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19953. "--"
  19954. ["Copy visible text" org-copy-visible t]
  19955. "--"
  19956. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19957. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19958. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19959. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19960. "--"
  19961. ["Sort Region/Children" org-sort t]
  19962. "--"
  19963. ["Convert to odd levels" org-convert-to-odd-levels t]
  19964. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19965. ("Editing"
  19966. ["Emphasis..." org-emphasize t]
  19967. ["Edit Source Example" org-edit-special t]
  19968. "--"
  19969. ["Footnote new/jump" org-footnote-action t]
  19970. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19971. ("Archive"
  19972. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19973. "--"
  19974. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19975. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19976. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19977. )
  19978. "--"
  19979. ("Hyperlinks"
  19980. ["Store Link (Global)" org-store-link t]
  19981. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19982. ["Insert Link" org-insert-link t]
  19983. ["Follow Link" org-open-at-point t]
  19984. "--"
  19985. ["Next link" org-next-link t]
  19986. ["Previous link" org-previous-link t]
  19987. "--"
  19988. ["Descriptive Links"
  19989. org-toggle-link-display
  19990. :style radio
  19991. :selected org-descriptive-links
  19992. ]
  19993. ["Literal Links"
  19994. org-toggle-link-display
  19995. :style radio
  19996. :selected (not org-descriptive-links)])
  19997. "--"
  19998. ("TODO Lists"
  19999. ["TODO/DONE/-" org-todo t]
  20000. ("Select keyword"
  20001. ["Next keyword" org-shiftright (org-at-heading-p)]
  20002. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  20003. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  20004. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  20005. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  20006. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  20007. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  20008. "--"
  20009. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  20010. :selected org-enforce-todo-dependencies :style toggle :active t]
  20011. "Settings for tree at point"
  20012. ["Do Children sequentially" org-toggle-ordered-property :style radio
  20013. :selected (org-entry-get nil "ORDERED")
  20014. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  20015. ["Do Children parallel" org-toggle-ordered-property :style radio
  20016. :selected (not (org-entry-get nil "ORDERED"))
  20017. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  20018. "--"
  20019. ["Set Priority" org-priority t]
  20020. ["Priority Up" org-shiftup t]
  20021. ["Priority Down" org-shiftdown t]
  20022. "--"
  20023. ["Get news from all feeds" org-feed-update-all t]
  20024. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  20025. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  20026. ("TAGS and Properties"
  20027. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  20028. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  20029. "--"
  20030. ["Set property" org-set-property (not (org-before-first-heading-p))]
  20031. ["Column view of properties" org-columns t]
  20032. ["Insert Column View DBlock" org-insert-columns-dblock t])
  20033. ("Dates and Scheduling"
  20034. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  20035. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  20036. ("Change Date"
  20037. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  20038. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  20039. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  20040. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  20041. ["Compute Time Range" org-evaluate-time-range t]
  20042. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  20043. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  20044. "--"
  20045. ["Custom time format" org-toggle-time-stamp-overlays
  20046. :style radio :selected org-display-custom-times]
  20047. "--"
  20048. ["Goto Calendar" org-goto-calendar t]
  20049. ["Date from Calendar" org-date-from-calendar t]
  20050. "--"
  20051. ["Start/Restart Timer" org-timer-start t]
  20052. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  20053. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  20054. ["Insert Timer String" org-timer t]
  20055. ["Insert Timer Item" org-timer-item t])
  20056. ("Logging work"
  20057. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  20058. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  20059. ["Clock out" org-clock-out t]
  20060. ["Clock cancel" org-clock-cancel t]
  20061. "--"
  20062. ["Mark as default task" org-clock-mark-default-task t]
  20063. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  20064. ["Goto running clock" org-clock-goto t]
  20065. "--"
  20066. ["Display times" org-clock-display t]
  20067. ["Create clock table" org-clock-report t]
  20068. "--"
  20069. ["Record DONE time"
  20070. (progn (setq org-log-done (not org-log-done))
  20071. (message "Switching to %s will %s record a timestamp"
  20072. (car org-done-keywords)
  20073. (if org-log-done "automatically" "not")))
  20074. :style toggle :selected org-log-done])
  20075. "--"
  20076. ["Agenda Command..." org-agenda t]
  20077. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  20078. ("File List for Agenda")
  20079. ("Special views current file"
  20080. ["TODO Tree" org-show-todo-tree t]
  20081. ["Check Deadlines" org-check-deadlines t]
  20082. ["Timeline" org-timeline t]
  20083. ["Tags/Property tree" org-match-sparse-tree t])
  20084. "--"
  20085. ["Export/Publish..." org-export-dispatch t]
  20086. ("LaTeX"
  20087. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  20088. :selected org-cdlatex-mode]
  20089. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  20090. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  20091. ["Modify math symbol" org-cdlatex-math-modify
  20092. (org-inside-LaTeX-fragment-p)]
  20093. ["Insert citation" org-reftex-citation t]
  20094. "--"
  20095. ["Template for BEAMER" (org-beamer-insert-options-template) t])
  20096. "--"
  20097. ("MobileOrg"
  20098. ["Push Files and Views" org-mobile-push t]
  20099. ["Get Captured and Flagged" org-mobile-pull t]
  20100. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  20101. "--"
  20102. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  20103. "--"
  20104. ("Documentation"
  20105. ["Show Version" org-version t]
  20106. ["Info Documentation" org-info t])
  20107. ("Customize"
  20108. ["Browse Org Group" org-customize t]
  20109. "--"
  20110. ["Expand This Menu" org-create-customize-menu
  20111. (fboundp 'customize-menu-create)])
  20112. ["Send bug report" org-submit-bug-report t]
  20113. "--"
  20114. ("Refresh/Reload"
  20115. ["Refresh setup current buffer" org-mode-restart t]
  20116. ["Reload Org (after update)" org-reload t]
  20117. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  20118. ))
  20119. (defun org-info (&optional node)
  20120. "Read documentation for Org-mode in the info system.
  20121. With optional NODE, go directly to that node."
  20122. (interactive)
  20123. (info (format "(org)%s" (or node ""))))
  20124. ;;;###autoload
  20125. (defun org-submit-bug-report ()
  20126. "Submit a bug report on Org-mode via mail.
  20127. Don't hesitate to report any problems or inaccurate documentation.
  20128. If you don't have setup sending mail from (X)Emacs, please copy the
  20129. output buffer into your mail program, as it gives us important
  20130. information about your Org-mode version and configuration."
  20131. (interactive)
  20132. (require 'reporter)
  20133. (defvar reporter-prompt-for-summary-p)
  20134. (org-load-modules-maybe)
  20135. (org-require-autoloaded-modules)
  20136. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  20137. (reporter-submit-bug-report
  20138. "emacs-orgmode@gnu.org"
  20139. (org-version nil 'full)
  20140. (let (list)
  20141. (save-window-excursion
  20142. (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  20143. (delete-other-windows)
  20144. (erase-buffer)
  20145. (insert "You are about to submit a bug report to the Org-mode mailing list.
  20146. We would like to add your full Org-mode and Outline configuration to the
  20147. bug report. This greatly simplifies the work of the maintainer and
  20148. other experts on the mailing list.
  20149. HOWEVER, some variables you have customized may contain private
  20150. information. The names of customers, colleagues, or friends, might
  20151. appear in the form of file names, tags, todo states, or search strings.
  20152. If you answer yes to the prompt, you might want to check and remove
  20153. such private information before sending the email.")
  20154. (add-text-properties (point-min) (point-max) '(face org-warning))
  20155. (when (yes-or-no-p "Include your Org-mode configuration ")
  20156. (mapatoms
  20157. (lambda (v)
  20158. (and (boundp v)
  20159. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  20160. (or (and (symbol-value v)
  20161. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  20162. (and
  20163. (get v 'custom-type) (get v 'standard-value)
  20164. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  20165. (push v list)))))
  20166. (kill-buffer (get-buffer "*Warn about privacy*"))
  20167. list))
  20168. nil nil
  20169. "Remember to cover the basics, that is, what you expected to happen and
  20170. what in fact did happen. You don't know how to make a good report? See
  20171. http://orgmode.org/manual/Feedback.html#Feedback
  20172. Your bug report will be posted to the Org-mode mailing list.
  20173. ------------------------------------------------------------------------")
  20174. (save-excursion
  20175. (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  20176. (replace-match "\\1Bug: \\3 [\\2]")))))
  20177. (defun org-install-agenda-files-menu ()
  20178. (let ((bl (buffer-list)))
  20179. (save-excursion
  20180. (while bl
  20181. (set-buffer (pop bl))
  20182. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20183. (when (derived-mode-p 'org-mode)
  20184. (easy-menu-change
  20185. '("Org") "File List for Agenda"
  20186. (append
  20187. (list
  20188. ["Edit File List" (org-edit-agenda-file-list) t]
  20189. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20190. ["Remove Current File from List" org-remove-file t]
  20191. ["Cycle through agenda files" org-cycle-agenda-files t]
  20192. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20193. "--")
  20194. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20195. ;;;; Documentation
  20196. (defun org-require-autoloaded-modules ()
  20197. (interactive)
  20198. (mapc 'require
  20199. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20200. org-table org-timer)))
  20201. ;;;###autoload
  20202. (defun org-reload (&optional uncompiled)
  20203. "Reload all org lisp files.
  20204. With prefix arg UNCOMPILED, load the uncompiled versions."
  20205. (interactive "P")
  20206. (require 'loadhist)
  20207. (let* ((org-dir (org-find-library-dir "org"))
  20208. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20209. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20210. (remove-re (mapconcat 'identity
  20211. (mapcar (lambda (f) (concat "^" f "$"))
  20212. (list (if (featurep 'xemacs)
  20213. "org-colview"
  20214. "org-colview-xemacs")
  20215. "org" "org-loaddefs" "org-version"))
  20216. "\\|"))
  20217. (feats (delete-dups
  20218. (mapcar 'file-name-sans-extension
  20219. (mapcar 'file-name-nondirectory
  20220. (delq nil
  20221. (mapcar 'feature-file
  20222. features))))))
  20223. (lfeat (append
  20224. (sort
  20225. (setq feats
  20226. (delq nil (mapcar
  20227. (lambda (f)
  20228. (if (and (string-match feature-re f)
  20229. (not (string-match remove-re f)))
  20230. f nil))
  20231. feats)))
  20232. 'string-lessp)
  20233. (list "org-version" "org")))
  20234. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20235. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20236. load-uncore load-misses)
  20237. (setq load-misses
  20238. (delq 't
  20239. (mapcar (lambda (f)
  20240. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20241. (and (string= org-dir contrib-dir)
  20242. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20243. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20244. (add-to-list 'load-uncore f 'append)
  20245. 't)
  20246. f))
  20247. lfeat)))
  20248. (when load-uncore
  20249. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20250. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20251. (if load-misses
  20252. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20253. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20254. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20255. ;;;###autoload
  20256. (defun org-customize ()
  20257. "Call the customize function with org as argument."
  20258. (interactive)
  20259. (org-load-modules-maybe)
  20260. (org-require-autoloaded-modules)
  20261. (customize-browse 'org))
  20262. (defun org-create-customize-menu ()
  20263. "Create a full customization menu for Org-mode, insert it into the menu."
  20264. (interactive)
  20265. (org-load-modules-maybe)
  20266. (org-require-autoloaded-modules)
  20267. (if (fboundp 'customize-menu-create)
  20268. (progn
  20269. (easy-menu-change
  20270. '("Org") "Customize"
  20271. `(["Browse Org group" org-customize t]
  20272. "--"
  20273. ,(customize-menu-create 'org)
  20274. ["Set" Custom-set t]
  20275. ["Save" Custom-save t]
  20276. ["Reset to Current" Custom-reset-current t]
  20277. ["Reset to Saved" Custom-reset-saved t]
  20278. ["Reset to Standard Settings" Custom-reset-standard t]))
  20279. (message "\"Org\"-menu now contains full customization menu"))
  20280. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20281. ;;;; Miscellaneous stuff
  20282. ;;; Generally useful functions
  20283. (defsubst org-get-at-eol (property n)
  20284. "Get text property PROPERTY at the end of line less N characters."
  20285. (get-text-property (- (point-at-eol) n) property))
  20286. (defun org-find-text-property-in-string (prop s)
  20287. "Return the first non-nil value of property PROP in string S."
  20288. (or (get-text-property 0 prop s)
  20289. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20290. prop s)))
  20291. (defun org-display-warning (message) ;; Copied from Emacs-Muse
  20292. "Display the given MESSAGE as a warning."
  20293. (if (fboundp 'display-warning)
  20294. (display-warning 'org message
  20295. (if (featurep 'xemacs) 'warning :warning))
  20296. (let ((buf (get-buffer-create "*Org warnings*")))
  20297. (with-current-buffer buf
  20298. (goto-char (point-max))
  20299. (insert "Warning (Org): " message)
  20300. (unless (bolp)
  20301. (newline)))
  20302. (display-buffer buf)
  20303. (sit-for 0))))
  20304. (defun org-eval (form)
  20305. "Eval FORM and return result."
  20306. (condition-case error
  20307. (eval form)
  20308. (error (format "%%![Error: %s]" error))))
  20309. (defun org-in-clocktable-p ()
  20310. "Check if the cursor is in a clocktable."
  20311. (let ((pos (point)) start)
  20312. (save-excursion
  20313. (end-of-line 1)
  20314. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20315. (setq start (match-beginning 0))
  20316. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20317. (>= (match-end 0) pos)
  20318. start))))
  20319. (defun org-in-verbatim-emphasis ()
  20320. (save-match-data
  20321. (and (org-in-regexp org-emph-re 2)
  20322. (>= (point) (match-beginning 3))
  20323. (<= (point) (match-end 4))
  20324. (member (match-string 3) '("=" "~")))))
  20325. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20326. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20327. (if (and marker (marker-buffer marker)
  20328. (buffer-live-p (marker-buffer marker)))
  20329. (progn
  20330. (org-pop-to-buffer-same-window (marker-buffer marker))
  20331. (when (or (> marker (point-max)) (< marker (point-min)))
  20332. (widen))
  20333. (goto-char marker)
  20334. (org-show-context 'org-goto))
  20335. (if bookmark
  20336. (bookmark-jump bookmark)
  20337. (error "Cannot find location"))))
  20338. (defun org-quote-csv-field (s)
  20339. "Quote field for inclusion in CSV material."
  20340. (if (string-match "[\",]" s)
  20341. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20342. s))
  20343. (defun org-force-self-insert (N)
  20344. "Needed to enforce self-insert under remapping."
  20345. (interactive "p")
  20346. (self-insert-command N))
  20347. (defun org-string-width (s)
  20348. "Compute width of string, ignoring invisible characters.
  20349. This ignores character with invisibility property `org-link', and also
  20350. characters with property `org-cwidth', because these will become invisible
  20351. upon the next fontification round."
  20352. (let (b l)
  20353. (when (or (eq t buffer-invisibility-spec)
  20354. (assq 'org-link buffer-invisibility-spec))
  20355. (while (setq b (text-property-any 0 (length s)
  20356. 'invisible 'org-link s))
  20357. (setq s (concat (substring s 0 b)
  20358. (substring s (or (next-single-property-change
  20359. b 'invisible s)
  20360. (length s)))))))
  20361. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20362. (setq s (concat (substring s 0 b)
  20363. (substring s (or (next-single-property-change
  20364. b 'org-cwidth s)
  20365. (length s))))))
  20366. (setq l (string-width s) b -1)
  20367. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20368. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20369. l))
  20370. (defun org-shorten-string (s maxlength)
  20371. "Shorten string S so tht it is no longer than MAXLENGTH characters.
  20372. If the string is shorter or has length MAXLENGTH, just return the
  20373. original string. If it is longer, the functions finds a space in the
  20374. string, breaks this string off at that locations and adds three dots
  20375. as ellipsis. Including the ellipsis, the string will not be longer
  20376. than MAXLENGTH. If finding a good breaking point in the string does
  20377. not work, the string is just chopped off in the middle of a word
  20378. if necessary."
  20379. (if (<= (length s) maxlength)
  20380. s
  20381. (let* ((n (max (- maxlength 4) 1))
  20382. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20383. (if (string-match re s)
  20384. (concat (match-string 1 s) "...")
  20385. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20386. (defun org-get-indentation (&optional line)
  20387. "Get the indentation of the current line, interpreting tabs.
  20388. When LINE is given, assume it represents a line and compute its indentation."
  20389. (if line
  20390. (when (string-match "^ *" (org-remove-tabs line))
  20391. (match-end 0))
  20392. (save-excursion
  20393. (beginning-of-line 1)
  20394. (skip-chars-forward " \t")
  20395. (current-column))))
  20396. (defun org-get-string-indentation (s)
  20397. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20398. (let ((n -1) (i 0) (w tab-width) c)
  20399. (catch 'exit
  20400. (while (< (setq n (1+ n)) (length s))
  20401. (setq c (aref s n))
  20402. (cond ((= c ?\ ) (setq i (1+ i)))
  20403. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20404. (t (throw 'exit t)))))
  20405. i))
  20406. (defun org-remove-tabs (s &optional width)
  20407. "Replace tabulators in S with spaces.
  20408. Assumes that s is a single line, starting in column 0."
  20409. (setq width (or width tab-width))
  20410. (while (string-match "\t" s)
  20411. (setq s (replace-match
  20412. (make-string
  20413. (- (* width (/ (+ (match-beginning 0) width) width))
  20414. (match-beginning 0)) ?\ )
  20415. t t s)))
  20416. s)
  20417. (defun org-fix-indentation (line ind)
  20418. "Fix indentation in LINE.
  20419. IND is a cons cell with target and minimum indentation.
  20420. If the current indentation in LINE is smaller than the minimum,
  20421. leave it alone. If it is larger than ind, set it to the target."
  20422. (let* ((l (org-remove-tabs line))
  20423. (i (org-get-indentation l))
  20424. (i1 (car ind)) (i2 (cdr ind)))
  20425. (when (>= i i2) (setq l (substring line i2)))
  20426. (if (> i1 0)
  20427. (concat (make-string i1 ?\ ) l)
  20428. l)))
  20429. (defun org-remove-indentation (code &optional n)
  20430. "Remove maximum common indentation in string CODE and return it.
  20431. N may optionally be the number of columns to remove. Return CODE
  20432. as-is if removal failed."
  20433. (with-temp-buffer
  20434. (insert code)
  20435. (if (org-do-remove-indentation n) (buffer-string) code)))
  20436. (defun org-do-remove-indentation (&optional n)
  20437. "Remove the maximum common indentation from the buffer.
  20438. When optional argument N is a positive integer, remove exactly
  20439. that much characters from indentation, if possible. Return nil
  20440. if it fails."
  20441. (catch :exit
  20442. (goto-char (point-min))
  20443. ;; Find maximum common indentation, if not specified.
  20444. (let ((n (or n
  20445. (let ((min-ind (point-max)))
  20446. (save-excursion
  20447. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20448. (let ((ind (1- (current-column))))
  20449. (if (zerop ind) (throw :exit nil)
  20450. (setq min-ind (min min-ind ind))))))
  20451. min-ind))))
  20452. (if (zerop n) (throw :exit nil)
  20453. ;; Remove exactly N indentation, but give up if not possible.
  20454. (while (not (eobp))
  20455. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20456. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20457. ((< ind n) (throw :exit nil))
  20458. (t (org-indent-line-to (- ind n))))
  20459. (forward-line)))
  20460. ;; Signal success.
  20461. t))))
  20462. (defun org-fill-template (template alist)
  20463. "Find each %key of ALIST in TEMPLATE and replace it."
  20464. (let ((case-fold-search nil))
  20465. (dolist (entry (sort (copy-sequence alist)
  20466. (lambda (a b) (< (length (car a)) (length (car b))))))
  20467. (setq template
  20468. (replace-regexp-in-string
  20469. (concat "%" (regexp-quote (car entry)))
  20470. (or (cdr entry) "") template t t)))
  20471. template))
  20472. (defun org-base-buffer (buffer)
  20473. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20474. (if (not buffer)
  20475. buffer
  20476. (or (buffer-base-buffer buffer)
  20477. buffer)))
  20478. (defun org-wrap (string &optional width lines)
  20479. "Wrap string to either a number of lines, or a width in characters.
  20480. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20481. that costs. If there is a word longer than WIDTH, the text is actually
  20482. wrapped to the length of that word.
  20483. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20484. many lines, whatever width that takes.
  20485. The return value is a list of lines, without newlines at the end."
  20486. (let* ((words (org-split-string string "[ \t\n]+"))
  20487. (maxword (apply 'max (mapcar 'org-string-width words)))
  20488. w ll)
  20489. (cond (width
  20490. (org-do-wrap words (max maxword width)))
  20491. (lines
  20492. (setq w maxword)
  20493. (setq ll (org-do-wrap words maxword))
  20494. (if (<= (length ll) lines)
  20495. ll
  20496. (setq ll words)
  20497. (while (> (length ll) lines)
  20498. (setq w (1+ w))
  20499. (setq ll (org-do-wrap words w)))
  20500. ll))
  20501. (t (error "Cannot wrap this")))))
  20502. (defun org-do-wrap (words width)
  20503. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20504. (let (lines line)
  20505. (while words
  20506. (setq line (pop words))
  20507. (while (and words (< (+ (length line) (length (car words))) width))
  20508. (setq line (concat line " " (pop words))))
  20509. (setq lines (push line lines)))
  20510. (nreverse lines)))
  20511. (defun org-split-string (string &optional separators)
  20512. "Splits STRING into substrings at SEPARATORS.
  20513. SEPARATORS is a regular expression.
  20514. No empty strings are returned if there are matches at the beginning
  20515. and end of string."
  20516. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20517. (let ((start 0) notfirst list)
  20518. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20519. (if (and notfirst
  20520. (= start (match-beginning 0))
  20521. (< start (length string)))
  20522. (1+ start) start))
  20523. (< (match-beginning 0) (length string)))
  20524. (setq notfirst t)
  20525. (or (eq (match-beginning 0) 0)
  20526. (and (eq (match-beginning 0) (match-end 0))
  20527. (eq (match-beginning 0) start))
  20528. (push (substring string start (match-beginning 0)) list))
  20529. (setq start (match-end 0)))
  20530. (or (eq start (length string))
  20531. (push (substring string start) list))
  20532. (nreverse list)))
  20533. (defun org-quote-vert (s)
  20534. "Replace \"|\" with \"\\vert\"."
  20535. (while (string-match "|" s)
  20536. (setq s (replace-match "\\vert" t t s)))
  20537. s)
  20538. (defun org-uuidgen-p (s)
  20539. "Is S an ID created by UUIDGEN?"
  20540. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20541. (defun org-in-src-block-p (&optional inside)
  20542. "Whether point is in a code source block.
  20543. When INSIDE is non-nil, don't consider we are within a src block
  20544. when point is at #+BEGIN_SRC or #+END_SRC."
  20545. (let ((case-fold-search t) ov)
  20546. (or (and (eq (get-char-property (point) 'src-block) t))
  20547. (and (not inside)
  20548. (save-match-data
  20549. (save-excursion
  20550. (beginning-of-line)
  20551. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20552. (defun org-context ()
  20553. "Return a list of contexts of the current cursor position.
  20554. If several contexts apply, all are returned.
  20555. Each context entry is a list with a symbol naming the context, and
  20556. two positions indicating start and end of the context. Possible
  20557. contexts are:
  20558. :headline anywhere in a headline
  20559. :headline-stars on the leading stars in a headline
  20560. :todo-keyword on a TODO keyword (including DONE) in a headline
  20561. :tags on the TAGS in a headline
  20562. :priority on the priority cookie in a headline
  20563. :item on the first line of a plain list item
  20564. :item-bullet on the bullet/number of a plain list item
  20565. :checkbox on the checkbox in a plain list item
  20566. :table in an org-mode table
  20567. :table-special on a special filed in a table
  20568. :table-table in a table.el table
  20569. :clocktable in a clocktable
  20570. :src-block in a source block
  20571. :link on a hyperlink
  20572. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20573. :target on a <<target>>
  20574. :radio-target on a <<<radio-target>>>
  20575. :latex-fragment on a LaTeX fragment
  20576. :latex-preview on a LaTeX fragment with overlaid preview image
  20577. This function expects the position to be visible because it uses font-lock
  20578. faces as a help to recognize the following contexts: :table-special, :link,
  20579. and :keyword."
  20580. (let* ((f (get-text-property (point) 'face))
  20581. (faces (if (listp f) f (list f)))
  20582. (case-fold-search t)
  20583. (p (point)) clist o)
  20584. ;; First the large context
  20585. (cond
  20586. ((org-at-heading-p t)
  20587. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20588. (when (progn
  20589. (beginning-of-line 1)
  20590. (looking-at org-todo-line-tags-regexp))
  20591. (push (org-point-in-group p 1 :headline-stars) clist)
  20592. (push (org-point-in-group p 2 :todo-keyword) clist)
  20593. (push (org-point-in-group p 4 :tags) clist))
  20594. (goto-char p)
  20595. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20596. (when (looking-at "\\[#[A-Z0-9]\\]")
  20597. (push (org-point-in-group p 0 :priority) clist)))
  20598. ((org-at-item-p)
  20599. (push (org-point-in-group p 2 :item-bullet) clist)
  20600. (push (list :item (point-at-bol)
  20601. (save-excursion (org-end-of-item) (point)))
  20602. clist)
  20603. (and (org-at-item-checkbox-p)
  20604. (push (org-point-in-group p 0 :checkbox) clist)))
  20605. ((org-at-table-p)
  20606. (push (list :table (org-table-begin) (org-table-end)) clist)
  20607. (when (memq 'org-formula faces)
  20608. (push (list :table-special
  20609. (previous-single-property-change p 'face)
  20610. (next-single-property-change p 'face)) clist)))
  20611. ((org-at-table-p 'any)
  20612. (push (list :table-table) clist)))
  20613. (goto-char p)
  20614. (let ((case-fold-search t))
  20615. ;; New the "medium" contexts: clocktables, source blocks
  20616. (cond ((org-in-clocktable-p)
  20617. (push (list :clocktable
  20618. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20619. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20620. (match-beginning 1))
  20621. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20622. (match-end 0))) clist))
  20623. ((org-in-src-block-p)
  20624. (push (list :src-block
  20625. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20626. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20627. (match-beginning 1))
  20628. (and (search-forward "#+END_SRC" nil t)
  20629. (match-beginning 0))) clist))))
  20630. (goto-char p)
  20631. ;; Now the small context
  20632. (cond
  20633. ((org-at-timestamp-p)
  20634. (push (org-point-in-group p 0 :timestamp) clist))
  20635. ((memq 'org-link faces)
  20636. (push (list :link
  20637. (previous-single-property-change p 'face)
  20638. (next-single-property-change p 'face)) clist))
  20639. ((memq 'org-special-keyword faces)
  20640. (push (list :keyword
  20641. (previous-single-property-change p 'face)
  20642. (next-single-property-change p 'face)) clist))
  20643. ((org-at-target-p)
  20644. (push (org-point-in-group p 0 :target) clist)
  20645. (goto-char (1- (match-beginning 0)))
  20646. (when (looking-at org-radio-target-regexp)
  20647. (push (org-point-in-group p 0 :radio-target) clist))
  20648. (goto-char p))
  20649. ((setq o (car (delq nil
  20650. (mapcar
  20651. (lambda (x)
  20652. (when (memq x org-latex-fragment-image-overlays) x))
  20653. (overlays-at (point))))))
  20654. (push (list :latex-fragment
  20655. (overlay-start o) (overlay-end o)) clist)
  20656. (push (list :latex-preview
  20657. (overlay-start o) (overlay-end o)) clist))
  20658. ((org-inside-LaTeX-fragment-p)
  20659. ;; FIXME: positions wrong.
  20660. (push (list :latex-fragment (point) (point)) clist)))
  20661. (setq clist (nreverse (delq nil clist)))
  20662. clist))
  20663. (defun org-in-regexp (regexp &optional nlines visually)
  20664. "Check if point is inside a match of REGEXP.
  20665. Normally only the current line is checked, but you can include
  20666. NLINES extra lines around point into the search. If VISUALLY is
  20667. set, require that the cursor is not after the match but really
  20668. on, so that the block visually is on the match.
  20669. Return nil or a cons cell (BEG . END) where BEG and END are,
  20670. respectively, the positions at the beginning and the end of the
  20671. match."
  20672. (catch :exit
  20673. (let ((pos (point))
  20674. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20675. (save-excursion
  20676. (beginning-of-line (- 1 (or nlines 0)))
  20677. (while (and (re-search-forward regexp eol t)
  20678. (<= (match-beginning 0) pos))
  20679. (let ((end (match-end 0)))
  20680. (when (or (> end pos) (and (= end pos) (not visually)))
  20681. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20682. (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
  20683. "Org mode 8.3")
  20684. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20685. "Non-nil when point is between matches of START-RE and END-RE.
  20686. Also return a non-nil value when point is on one of the matches.
  20687. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20688. buffer positions. Default values are the positions of headlines
  20689. surrounding the point.
  20690. The functions returns a cons cell whose car (resp. cdr) is the
  20691. position before START-RE (resp. after END-RE)."
  20692. (save-match-data
  20693. (let ((pos (point))
  20694. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20695. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20696. beg end)
  20697. (save-excursion
  20698. ;; Point is on a block when on START-RE or if START-RE can be
  20699. ;; found before it...
  20700. (and (or (org-in-regexp start-re)
  20701. (re-search-backward start-re limit-up t))
  20702. (setq beg (match-beginning 0))
  20703. ;; ... and END-RE after it...
  20704. (goto-char (match-end 0))
  20705. (re-search-forward end-re limit-down t)
  20706. (> (setq end (match-end 0)) pos)
  20707. ;; ... without another START-RE in-between.
  20708. (goto-char (match-beginning 0))
  20709. (not (re-search-backward start-re (1+ beg) t))
  20710. ;; Return value.
  20711. (cons beg end))))))
  20712. (defun org-in-block-p (names)
  20713. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20714. NAMES is a list of strings containing names of blocks.
  20715. Return first block name matched, or nil. Beware that in case of
  20716. nested blocks, the returned name may not belong to the closest
  20717. block from point."
  20718. (save-match-data
  20719. (catch 'exit
  20720. (let ((case-fold-search t)
  20721. (lim-up (save-excursion (outline-previous-heading)))
  20722. (lim-down (save-excursion (outline-next-heading))))
  20723. (mapc (lambda (name)
  20724. (let ((n (regexp-quote name)))
  20725. (when (org-between-regexps-p
  20726. (concat "^[ \t]*#\\+begin_" n)
  20727. (concat "^[ \t]*#\\+end_" n)
  20728. lim-up lim-down)
  20729. (throw 'exit n))))
  20730. names))
  20731. nil)))
  20732. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20733. "Call `multi-occur' with buffers for all agenda files."
  20734. (interactive "sOrg-files matching: ")
  20735. (let* ((files (org-agenda-files))
  20736. (tnames (mapcar #'file-truename files))
  20737. (extra org-agenda-text-search-extra-files))
  20738. (when (eq (car extra) 'agenda-archives)
  20739. (setq extra (cdr extra))
  20740. (setq files (org-add-archive-files files)))
  20741. (dolist (f extra)
  20742. (unless (member (file-truename f) tnames)
  20743. (unless (member f files) (setq files (append files (list f))))
  20744. (setq tnames (append tnames (list (file-truename f))))))
  20745. (multi-occur
  20746. (mapcar (lambda (x)
  20747. (with-current-buffer
  20748. ;; FIXME: Why not just (find-file-noselect x)?
  20749. ;; Is it to avoid the "revert buffer" prompt?
  20750. (or (get-file-buffer x) (find-file-noselect x))
  20751. (widen)
  20752. (current-buffer)))
  20753. files)
  20754. regexp)))
  20755. (if (boundp 'occur-mode-find-occurrence-hook)
  20756. ;; Emacs 23
  20757. (add-hook 'occur-mode-find-occurrence-hook
  20758. (lambda ()
  20759. (when (derived-mode-p 'org-mode)
  20760. (org-reveal))))
  20761. ;; Emacs 22
  20762. (defadvice occur-mode-goto-occurrence
  20763. (after org-occur-reveal activate)
  20764. (and (derived-mode-p 'org-mode) (org-reveal)))
  20765. (defadvice occur-mode-goto-occurrence-other-window
  20766. (after org-occur-reveal activate)
  20767. (and (derived-mode-p 'org-mode) (org-reveal)))
  20768. (defadvice occur-mode-display-occurrence
  20769. (after org-occur-reveal activate)
  20770. (when (derived-mode-p 'org-mode)
  20771. (let ((pos (occur-mode-find-occurrence)))
  20772. (with-current-buffer (marker-buffer pos)
  20773. (save-excursion
  20774. (goto-char pos)
  20775. (org-reveal)))))))
  20776. (defun org-occur-link-in-agenda-files ()
  20777. "Create a link and search for it in the agendas.
  20778. The link is not stored in `org-stored-links', it is just created
  20779. for the search purpose."
  20780. (interactive)
  20781. (let ((link (condition-case nil
  20782. (org-store-link nil)
  20783. (error "Unable to create a link to here"))))
  20784. (org-occur-in-agenda-files (regexp-quote link))))
  20785. (defun org-reverse-string (string)
  20786. "Return the reverse of STRING."
  20787. (apply 'string (reverse (string-to-list string))))
  20788. ;; defsubst org-uniquify must be defined before first use
  20789. (defun org-uniquify-alist (alist)
  20790. "Merge elements of ALIST with the same key.
  20791. For example, in this alist:
  20792. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20793. => \\='((a 1 3) (b 2))
  20794. merge (a 1) and (a 3) into (a 1 3).
  20795. The function returns the new ALIST."
  20796. (let (rtn)
  20797. (mapc
  20798. (lambda (e)
  20799. (let (n)
  20800. (if (not (assoc (car e) rtn))
  20801. (push e rtn)
  20802. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20803. (setq rtn (assq-delete-all (car e) rtn))
  20804. (push n rtn))))
  20805. alist)
  20806. rtn))
  20807. (defun org-delete-all (elts list)
  20808. "Remove all elements in ELTS from LIST."
  20809. (while elts
  20810. (setq list (delete (pop elts) list)))
  20811. list)
  20812. (defun org-back-over-empty-lines ()
  20813. "Move backwards over whitespace, to the beginning of the first empty line.
  20814. Returns the number of empty lines passed."
  20815. (let ((pos (point)))
  20816. (if (cdr (assoc 'heading org-blank-before-new-entry))
  20817. (skip-chars-backward " \t\n\r")
  20818. (unless (eobp)
  20819. (forward-line -1)))
  20820. (beginning-of-line 2)
  20821. (goto-char (min (point) pos))
  20822. (count-lines (point) pos)))
  20823. (defun org-skip-whitespace ()
  20824. (skip-chars-forward " \t\n\r"))
  20825. (defun org-point-in-group (point group &optional context)
  20826. "Check if POINT is in match-group GROUP.
  20827. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20828. match. If the match group does not exist or point is not inside it,
  20829. return nil."
  20830. (and (match-beginning group)
  20831. (>= point (match-beginning group))
  20832. (<= point (match-end group))
  20833. (if context
  20834. (list context (match-beginning group) (match-end group))
  20835. t)))
  20836. (defun org-switch-to-buffer-other-window (&rest args)
  20837. "Switch to buffer in a second window on the current frame.
  20838. In particular, do not allow pop-up frames.
  20839. Returns the newly created buffer."
  20840. (org-no-popups
  20841. (apply 'switch-to-buffer-other-window args)))
  20842. (defun org-combine-plists (&rest plists)
  20843. "Create a single property list from all plists in PLISTS.
  20844. The process starts by copying the first list, and then setting properties
  20845. from the other lists. Settings in the last list are the most significant
  20846. ones and overrule settings in the other lists."
  20847. (let ((rtn (copy-sequence (pop plists)))
  20848. p v ls)
  20849. (while plists
  20850. (setq ls (pop plists))
  20851. (while ls
  20852. (setq p (pop ls) v (pop ls))
  20853. (setq rtn (plist-put rtn p v))))
  20854. rtn))
  20855. (defun org-replace-escapes (string table)
  20856. "Replace %-escapes in STRING with values in TABLE.
  20857. TABLE is an association list with keys like \"%a\" and string values.
  20858. The sequences in STRING may contain normal field width and padding information,
  20859. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20860. so values can contain further %-escapes if they are define later in TABLE."
  20861. (let ((tbl (copy-alist table))
  20862. (case-fold-search nil)
  20863. (pchg 0)
  20864. e re rpl)
  20865. (dolist (e tbl)
  20866. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20867. (when (and (cdr e) (string-match re (cdr e)))
  20868. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20869. (safe "SREF"))
  20870. (add-text-properties 0 3 (list 'sref sref) safe)
  20871. (setcdr e (replace-match safe t t (cdr e)))))
  20872. (while (string-match re string)
  20873. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20874. (cdr e)))
  20875. (setq string (replace-match rpl t t string))))
  20876. (while (setq pchg (next-property-change pchg string))
  20877. (let ((sref (get-text-property pchg 'sref string)))
  20878. (when (and sref (string-match "SREF" string pchg))
  20879. (setq string (replace-match sref t t string)))))
  20880. string))
  20881. (defun org-sublist (list start end)
  20882. "Return a section of LIST, from START to END.
  20883. Counting starts at 1."
  20884. (cl-subseq list (1- start) end))
  20885. (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
  20886. (defun org-find-base-buffer-visiting (file)
  20887. "Like `find-buffer-visiting' but always return the base buffer and
  20888. not an indirect buffer."
  20889. (let ((buf (or (get-file-buffer file)
  20890. (find-buffer-visiting file))))
  20891. (if buf
  20892. (or (buffer-base-buffer buf) buf)
  20893. nil)))
  20894. (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
  20895. "Org 9.0")
  20896. ;;; TODO: Only called once, from ox-odt which should probably use
  20897. ;;; org-export-inline-image-p or something.
  20898. (defun org-file-image-p (file)
  20899. "Return non-nil if FILE is an image."
  20900. (save-match-data
  20901. (string-match (image-file-name-regexp) file)))
  20902. (defun org-get-cursor-date (&optional with-time)
  20903. "Return the date at cursor in as a time.
  20904. This works in the calendar and in the agenda, anywhere else it just
  20905. returns the current time.
  20906. If WITH-TIME is non-nil, returns the time of the event at point (in
  20907. the agenda) or the current time of the day."
  20908. (let (date day defd tp hod mod)
  20909. (when with-time
  20910. (setq tp (get-text-property (point) 'time))
  20911. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20912. (setq hod (string-to-number (match-string 1 tp))
  20913. mod (string-to-number (match-string 2 tp))))
  20914. (or tp (let ((now (decode-time)))
  20915. (setq hod (nth 2 now)
  20916. mod (nth 1 now)))))
  20917. (cond
  20918. ((eq major-mode 'calendar-mode)
  20919. (setq date (calendar-cursor-to-date)
  20920. defd (encode-time 0 (or mod 0) (or hod 0)
  20921. (nth 1 date) (nth 0 date) (nth 2 date))))
  20922. ((eq major-mode 'org-agenda-mode)
  20923. (setq day (get-text-property (point) 'day))
  20924. (when day
  20925. (setq date (calendar-gregorian-from-absolute day)
  20926. defd (encode-time 0 (or mod 0) (or hod 0)
  20927. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20928. (or defd (current-time))))
  20929. (defun org-mark-subtree (&optional up)
  20930. "Mark the current subtree.
  20931. This puts point at the start of the current subtree, and mark at
  20932. the end. If a numeric prefix UP is given, move up into the
  20933. hierarchy of headlines by UP levels before marking the subtree."
  20934. (interactive "P")
  20935. (org-with-limited-levels
  20936. (cond ((org-at-heading-p) (beginning-of-line))
  20937. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20938. (t (outline-previous-visible-heading 1))))
  20939. (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
  20940. (if (org-called-interactively-p 'any)
  20941. (call-interactively 'org-mark-element)
  20942. (org-mark-element)))
  20943. ;;; Indentation
  20944. (defun org--get-expected-indentation (element contentsp)
  20945. "Expected indentation column for current line, according to ELEMENT.
  20946. ELEMENT is an element containing point. CONTENTSP is non-nil
  20947. when indentation is to be computed according to contents of
  20948. ELEMENT."
  20949. (let ((type (org-element-type element))
  20950. (start (org-element-property :begin element))
  20951. (post-affiliated (org-element-property :post-affiliated element)))
  20952. (org-with-wide-buffer
  20953. (cond
  20954. (contentsp
  20955. (case type
  20956. ((diary-sexp footnote-definition) 0)
  20957. ((headline inlinetask nil)
  20958. (if (not org-adapt-indentation) 0
  20959. (let ((level (org-current-level)))
  20960. (if level (1+ level) 0))))
  20961. ((item plain-list) (org-list-item-body-column post-affiliated))
  20962. (t
  20963. (goto-char start)
  20964. (org-get-indentation))))
  20965. ((memq type '(headline inlinetask nil))
  20966. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20967. (org--get-expected-indentation element t)
  20968. 0))
  20969. ((memq type '(diary-sexp footnote-definition)) 0)
  20970. ;; First paragraph of a footnote definition or an item.
  20971. ;; Indent like parent.
  20972. ((< (line-beginning-position) start)
  20973. (org--get-expected-indentation
  20974. (org-element-property :parent element) t))
  20975. ;; At first line: indent according to previous sibling, if any,
  20976. ;; ignoring footnote definitions and inline tasks, or parent's
  20977. ;; contents.
  20978. ((= (line-beginning-position) start)
  20979. (catch 'exit
  20980. (while t
  20981. (if (= (point-min) start) (throw 'exit 0)
  20982. (goto-char (1- start))
  20983. (let* ((previous (org-element-at-point))
  20984. (parent previous))
  20985. (while (and parent (<= (org-element-property :end parent) start))
  20986. (setq previous parent
  20987. parent (org-element-property :parent parent)))
  20988. (cond
  20989. ((not previous) (throw 'exit 0))
  20990. ((> (org-element-property :end previous) start)
  20991. (throw 'exit (org--get-expected-indentation previous t)))
  20992. ((memq (org-element-type previous)
  20993. '(footnote-definition inlinetask))
  20994. (setq start (org-element-property :begin previous)))
  20995. (t (goto-char (org-element-property :begin previous))
  20996. (throw 'exit
  20997. (if (bolp) (org-get-indentation)
  20998. ;; At first paragraph in an item or
  20999. ;; a footnote definition.
  21000. (org--get-expected-indentation
  21001. (org-element-property :parent previous) t))))))))))
  21002. ;; Otherwise, move to the first non-blank line above.
  21003. (t
  21004. (beginning-of-line)
  21005. (let ((pos (point)))
  21006. (skip-chars-backward " \r\t\n")
  21007. (cond
  21008. ;; Two blank lines end a footnote definition or a plain
  21009. ;; list. When we indent an empty line after them, the
  21010. ;; containing list or footnote definition is over, so it
  21011. ;; qualifies as a previous sibling. Therefore, we indent
  21012. ;; like its first line.
  21013. ((and (memq type '(footnote-definition plain-list))
  21014. (> (count-lines (point) pos) 2))
  21015. (goto-char start)
  21016. (org-get-indentation))
  21017. ;; Line above is the first one of a paragraph at the
  21018. ;; beginning of an item or a footnote definition. Indent
  21019. ;; like parent.
  21020. ((< (line-beginning-position) start)
  21021. (org--get-expected-indentation
  21022. (org-element-property :parent element) t))
  21023. ;; Line above is the beginning of an element, i.e., point
  21024. ;; was originally on the blank lines between element's start
  21025. ;; and contents.
  21026. ((= (line-beginning-position) post-affiliated)
  21027. (org--get-expected-indentation element t))
  21028. ;; POS is after contents in a greater element. Indent like
  21029. ;; the beginning of the element.
  21030. ;;
  21031. ;; As a special case, if point is at the end of a footnote
  21032. ;; definition or an item, indent like the very last element
  21033. ;; within.
  21034. ((and (not (eq type 'paragraph))
  21035. (let ((cend (org-element-property :contents-end element)))
  21036. (and cend (<= cend pos))))
  21037. (if (memq type '(footnote-definition item plain-list))
  21038. (let ((last (org-element-at-point)))
  21039. (org--get-expected-indentation
  21040. last
  21041. (memq (org-element-type last)
  21042. '(footnote-definition item plain-list))))
  21043. (goto-char start)
  21044. (org-get-indentation)))
  21045. ;; In any other case, indent like the current line.
  21046. (t (org-get-indentation)))))))))
  21047. (defun org--align-node-property ()
  21048. "Align node property at point.
  21049. Alignment is done according to `org-property-format', which see."
  21050. (when (save-excursion
  21051. (beginning-of-line)
  21052. (looking-at org-property-re))
  21053. (replace-match
  21054. (concat (match-string 4)
  21055. (org-trim
  21056. (format org-property-format (match-string 1) (match-string 3))))
  21057. t t)))
  21058. (defun org-indent-line ()
  21059. "Indent line depending on context.
  21060. Indentation is done according to the following rules:
  21061. - Footnote definitions, diary sexps, headlines and inline tasks
  21062. have to start at column 0.
  21063. - On the very first line of an element, consider, in order, the
  21064. next rules until one matches:
  21065. 1. If there's a sibling element before, ignoring footnote
  21066. definitions and inline tasks, indent like its first line.
  21067. 2. If element has a parent, indent like its contents. More
  21068. precisely, if parent is an item, indent after the
  21069. description part, if any, or the bullet (see
  21070. `org-list-description-max-indent'). Else, indent like
  21071. parent's first line.
  21072. 3. Otherwise, indent relatively to current level, if
  21073. `org-adapt-indentation' is non-nil, or to left margin.
  21074. - On a blank line at the end of an element, indent according to
  21075. the type of the element. More precisely
  21076. 1. If element is a plain list, an item, or a footnote
  21077. definition, indent like the very last element within.
  21078. 2. If element is a paragraph, indent like its last non blank
  21079. line.
  21080. 3. Otherwise, indent like its very first line.
  21081. - In the code part of a source block, use language major mode
  21082. to indent current line if `org-src-tab-acts-natively' is
  21083. non-nil. If it is nil, do nothing.
  21084. - Otherwise, indent like the first non-blank line above.
  21085. The function doesn't indent an item as it could break the whole
  21086. list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
  21087. \\[org-shiftmetaright].
  21088. Also align node properties according to `org-property-format'."
  21089. (interactive)
  21090. (cond
  21091. (orgstruct-is-++
  21092. (let ((indent-line-function
  21093. (cadadr (assq 'indent-line-function org-fb-vars))))
  21094. (indent-according-to-mode)))
  21095. ((org-at-heading-p) 'noindent)
  21096. (t
  21097. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  21098. (type (org-element-type element)))
  21099. (cond ((and (memq type '(plain-list item))
  21100. (= (line-beginning-position)
  21101. (org-element-property :post-affiliated element)))
  21102. 'noindent)
  21103. ((and (eq type 'src-block)
  21104. org-src-tab-acts-natively
  21105. (> (line-beginning-position)
  21106. (org-element-property :post-affiliated element))
  21107. (< (line-beginning-position)
  21108. (org-with-wide-buffer
  21109. (goto-char (org-element-property :end element))
  21110. (skip-chars-backward " \r\t\n")
  21111. (line-beginning-position))))
  21112. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  21113. (t
  21114. (let ((column (org--get-expected-indentation element nil)))
  21115. ;; Preserve current column.
  21116. (if (<= (current-column) (current-indentation))
  21117. (org-indent-line-to column)
  21118. (save-excursion (org-indent-line-to column))))
  21119. ;; Align node property. Also preserve current column.
  21120. (when (eq type 'node-property)
  21121. (let ((column (current-column)))
  21122. (org--align-node-property)
  21123. (org-move-to-column column)))))))))
  21124. (defun org-indent-region (start end)
  21125. "Indent each non-blank line in the region.
  21126. Called from a program, START and END specify the region to
  21127. indent. The function will not indent contents of example blocks,
  21128. verse blocks and export blocks as leading white spaces are
  21129. assumed to be significant there."
  21130. (interactive "r")
  21131. (save-excursion
  21132. (goto-char start)
  21133. (skip-chars-forward " \r\t\n")
  21134. (unless (eobp) (beginning-of-line))
  21135. (let ((indent-to
  21136. (lambda (ind pos)
  21137. ;; Set IND as indentation for all lines between point and
  21138. ;; POS or END, whichever comes first. Blank lines are
  21139. ;; ignored. Leave point after POS once done.
  21140. (let ((limit (copy-marker (min end pos))))
  21141. (while (< (point) limit)
  21142. (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
  21143. (forward-line))
  21144. (set-marker limit nil))))
  21145. (end (copy-marker end)))
  21146. (while (< (point) end)
  21147. (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21148. (let* ((element (org-element-at-point))
  21149. (type (org-element-type element))
  21150. (element-end (copy-marker (org-element-property :end element)))
  21151. (ind (org--get-expected-indentation element nil)))
  21152. (cond
  21153. ((or (memq type '(paragraph table table-row))
  21154. (not (or (org-element-property :contents-begin element)
  21155. (memq type
  21156. '(example-block export-block src-block)))))
  21157. ;; Elements here are indented as a single block. Also
  21158. ;; align node properties.
  21159. (when (eq type 'node-property)
  21160. (org--align-node-property)
  21161. (beginning-of-line))
  21162. (funcall indent-to ind element-end))
  21163. (t
  21164. ;; Elements in this category consist of three parts:
  21165. ;; before the contents, the contents, and after the
  21166. ;; contents. The contents are treated specially,
  21167. ;; according to the element type, or not indented at
  21168. ;; all. Other parts are indented as a single block.
  21169. (let* ((post (copy-marker
  21170. (org-element-property :post-affiliated element)))
  21171. (cbeg
  21172. (copy-marker
  21173. (cond
  21174. ((not (org-element-property :contents-begin element))
  21175. ;; Fake contents for source blocks.
  21176. (org-with-wide-buffer
  21177. (goto-char post)
  21178. (forward-line)
  21179. (point)))
  21180. ((memq type '(footnote-definition item plain-list))
  21181. ;; Contents in these elements could start on
  21182. ;; the same line as the beginning of the
  21183. ;; element. Make sure we start indenting
  21184. ;; from the second line.
  21185. (org-with-wide-buffer
  21186. (goto-char post)
  21187. (end-of-line)
  21188. (skip-chars-forward " \r\t\n")
  21189. (if (eobp) (point) (line-beginning-position))))
  21190. (t (org-element-property :contents-begin element)))))
  21191. (cend (copy-marker
  21192. (or (org-element-property :contents-end element)
  21193. ;; Fake contents for source blocks.
  21194. (org-with-wide-buffer
  21195. (goto-char element-end)
  21196. (skip-chars-backward " \r\t\n")
  21197. (line-beginning-position)))
  21198. t)))
  21199. ;; Do not change items indentation individually as it
  21200. ;; might break the list as a whole. On the other
  21201. ;; hand, when at a plain list, indent it as a whole.
  21202. (cond ((eq type 'plain-list)
  21203. (let ((offset (- ind (org-get-indentation))))
  21204. (unless (zerop offset)
  21205. (indent-rigidly (org-element-property :begin element)
  21206. (org-element-property :end element)
  21207. offset))
  21208. (goto-char cbeg)))
  21209. ((eq type 'item) (goto-char cbeg))
  21210. (t (funcall indent-to ind cbeg)))
  21211. (when (< (point) end)
  21212. (case type
  21213. ((example-block export-block verse-block))
  21214. (src-block
  21215. ;; In a source block, indent source code
  21216. ;; according to language major mode, but only if
  21217. ;; `org-src-tab-acts-natively' is non-nil.
  21218. (when (and (< (point) end) org-src-tab-acts-natively)
  21219. (ignore-errors
  21220. (org-babel-do-in-edit-buffer
  21221. (indent-region (point-min) (point-max))))))
  21222. (t (org-indent-region (point) (min cend end))))
  21223. (goto-char (min cend end))
  21224. (when (< (point) end) (funcall indent-to ind element-end)))
  21225. (set-marker post nil)
  21226. (set-marker cbeg nil)
  21227. (set-marker cend nil))))
  21228. (set-marker element-end nil))))
  21229. (set-marker end nil))))
  21230. (defun org-indent-drawer ()
  21231. "Indent the drawer at point."
  21232. (interactive)
  21233. (unless (save-excursion
  21234. (beginning-of-line)
  21235. (org-looking-at-p org-drawer-regexp))
  21236. (user-error "Not at a drawer"))
  21237. (let ((element (org-element-at-point)))
  21238. (unless (memq (org-element-type element) '(drawer property-drawer))
  21239. (user-error "Not at a drawer"))
  21240. (org-with-wide-buffer
  21241. (org-indent-region (org-element-property :begin element)
  21242. (org-element-property :end element))))
  21243. (message "Drawer at point indented"))
  21244. (defun org-indent-block ()
  21245. "Indent the block at point."
  21246. (interactive)
  21247. (unless (save-excursion
  21248. (beginning-of-line)
  21249. (let ((case-fold-search t))
  21250. (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21251. (user-error "Not at a block"))
  21252. (let ((element (org-element-at-point)))
  21253. (unless (memq (org-element-type element)
  21254. '(comment-block center-block dynamic-block example-block
  21255. export-block quote-block special-block
  21256. src-block verse-block))
  21257. (user-error "Not at a block"))
  21258. (org-with-wide-buffer
  21259. (org-indent-region (org-element-property :begin element)
  21260. (org-element-property :end element))))
  21261. (message "Block at point indented"))
  21262. ;;; Filling
  21263. ;; We use our own fill-paragraph and auto-fill functions.
  21264. ;; `org-fill-paragraph' relies on adaptive filling and context
  21265. ;; checking. Appropriate `fill-prefix' is computed with
  21266. ;; `org-adaptive-fill-function'.
  21267. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21268. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21269. ;; `org-adaptive-fill-function' value. Internally,
  21270. ;; `org-comment-line-break-function' breaks the line.
  21271. ;; `org-setup-filling' installs filling and auto-filling related
  21272. ;; variables during `org-mode' initialization.
  21273. (defvar org-element-paragraph-separate) ; org-element.el
  21274. (defun org-setup-filling ()
  21275. (require 'org-element)
  21276. ;; Prevent auto-fill from inserting unwanted new items.
  21277. (when (boundp 'fill-nobreak-predicate)
  21278. (setq-local
  21279. fill-nobreak-predicate
  21280. (org-uniquify
  21281. (append fill-nobreak-predicate
  21282. '(org-fill-line-break-nobreak-p
  21283. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21284. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21285. (setq-local paragraph-start paragraph-ending)
  21286. (setq-local paragraph-separate paragraph-ending))
  21287. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21288. (setq-local auto-fill-inhibit-regexp nil)
  21289. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21290. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21291. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21292. (defun org-fill-line-break-nobreak-p ()
  21293. "Non-nil when a new line at point would create an Org line break."
  21294. (save-excursion
  21295. (skip-chars-backward "[ \t]")
  21296. (skip-chars-backward "\\\\")
  21297. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21298. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21299. "Non-nil when a new line at point would split a timestamp."
  21300. (and (org-at-timestamp-p t)
  21301. (not (looking-at org-ts-regexp-both))))
  21302. (declare-function message-in-body-p "message" ())
  21303. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21304. (defun org-adaptive-fill-function ()
  21305. "Compute a fill prefix for the current line.
  21306. Return fill prefix, as a string, or nil if current line isn't
  21307. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21308. matches in paragraphs or comments, use it."
  21309. (catch 'exit
  21310. (when (derived-mode-p 'message-mode)
  21311. (save-excursion
  21312. (beginning-of-line)
  21313. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21314. ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
  21315. ((looking-at message-cite-prefix-regexp)
  21316. (throw 'exit (match-string-no-properties 0)))
  21317. ((looking-at org-outline-regexp)
  21318. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21319. (org-with-wide-buffer
  21320. (unless (org-at-heading-p)
  21321. (let* ((p (line-beginning-position))
  21322. (element (save-excursion
  21323. (beginning-of-line)
  21324. (org-element-at-point)))
  21325. (type (org-element-type element))
  21326. (post-affiliated (org-element-property :post-affiliated element)))
  21327. (unless (< p post-affiliated)
  21328. (case type
  21329. (comment
  21330. (save-excursion
  21331. (beginning-of-line)
  21332. (looking-at "[ \t]*")
  21333. (concat (match-string 0) "# ")))
  21334. (footnote-definition "")
  21335. ((item plain-list)
  21336. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21337. (paragraph
  21338. ;; Fill prefix is usually the same as the current line,
  21339. ;; unless the paragraph is at the beginning of an item.
  21340. (let ((parent (org-element-property :parent element)))
  21341. (save-excursion
  21342. (beginning-of-line)
  21343. (cond ((eq (org-element-type parent) 'item)
  21344. (make-string (org-list-item-body-column
  21345. (org-element-property :begin parent))
  21346. ?\s))
  21347. ((and adaptive-fill-regexp
  21348. ;; Locally disable
  21349. ;; `adaptive-fill-function' to let
  21350. ;; `fill-context-prefix' handle
  21351. ;; `adaptive-fill-regexp' variable.
  21352. (let (adaptive-fill-function)
  21353. (fill-context-prefix
  21354. post-affiliated
  21355. (org-element-property :end element)))))
  21356. ((looking-at "[ \t]+") (match-string 0))
  21357. (t "")))))
  21358. (comment-block
  21359. ;; Only fill contents if P is within block boundaries.
  21360. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21361. (forward-line)
  21362. (point)))
  21363. (cend (save-excursion
  21364. (goto-char (org-element-property :end element))
  21365. (skip-chars-backward " \r\t\n")
  21366. (line-beginning-position))))
  21367. (when (and (>= p cbeg) (< p cend))
  21368. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21369. (match-string 0)
  21370. "")))))))))))
  21371. (declare-function message-goto-body "message" ())
  21372. (defvar message-cite-prefix-regexp) ; From message.el
  21373. (defun org-fill-paragraph (&optional justify)
  21374. "Fill element at point, when applicable.
  21375. This function only applies to comment blocks, comments, example
  21376. blocks and paragraphs. Also, as a special case, re-align table
  21377. when point is at one.
  21378. If JUSTIFY is non-nil (interactively, with prefix argument),
  21379. justify as well. If `sentence-end-double-space' is non-nil, then
  21380. period followed by one space does not end a sentence, so don't
  21381. break a line there. The variable `fill-column' controls the
  21382. width for filling.
  21383. For convenience, when point is at a plain list, an item or
  21384. a footnote definition, try to fill the first paragraph within."
  21385. (interactive)
  21386. (if (and (derived-mode-p 'message-mode)
  21387. (or (not (message-in-body-p))
  21388. (save-excursion (move-beginning-of-line 1)
  21389. (looking-at message-cite-prefix-regexp))))
  21390. ;; First ensure filling is correct in message-mode.
  21391. (let ((fill-paragraph-function
  21392. (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
  21393. (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
  21394. (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
  21395. (paragraph-separate
  21396. (cadadr (assoc 'paragraph-separate org-fb-vars))))
  21397. (fill-paragraph nil))
  21398. (with-syntax-table org-mode-transpose-word-syntax-table
  21399. ;; Move to end of line in order to get the first paragraph
  21400. ;; within a plain list or a footnote definition.
  21401. (let ((element (save-excursion
  21402. (end-of-line)
  21403. (or (ignore-errors (org-element-at-point))
  21404. (user-error "An element cannot be parsed line %d"
  21405. (line-number-at-pos (point)))))))
  21406. ;; First check if point is in a blank line at the beginning of
  21407. ;; the buffer. In that case, ignore filling.
  21408. (case (org-element-type element)
  21409. ;; Use major mode filling function is src blocks.
  21410. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21411. ;; Align Org tables, leave table.el tables as-is.
  21412. (table-row (org-table-align) t)
  21413. (table
  21414. (when (eq (org-element-property :type element) 'org)
  21415. (save-excursion
  21416. (goto-char (org-element-property :post-affiliated element))
  21417. (org-table-align)))
  21418. t)
  21419. (paragraph
  21420. ;; Paragraphs may contain `line-break' type objects.
  21421. (let ((beg (max (point-min)
  21422. (org-element-property :contents-begin element)))
  21423. (end (min (point-max)
  21424. (org-element-property :contents-end element))))
  21425. ;; Do nothing if point is at an affiliated keyword.
  21426. (if (< (line-end-position) beg) t
  21427. (when (derived-mode-p 'message-mode)
  21428. ;; In `message-mode', do not fill following citation
  21429. ;; in current paragraph nor text before message body.
  21430. (let ((body-start (save-excursion (message-goto-body))))
  21431. (when body-start (setq beg (max body-start beg))))
  21432. (when (save-excursion
  21433. (re-search-forward
  21434. (concat "^" message-cite-prefix-regexp) end t))
  21435. (setq end (match-beginning 0))))
  21436. ;; Fill paragraph, taking line breaks into account.
  21437. (save-excursion
  21438. (goto-char beg)
  21439. (let ((cuts (list beg)))
  21440. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21441. (when (eq 'line-break
  21442. (org-element-type
  21443. (save-excursion (backward-char)
  21444. (org-element-context))))
  21445. (push (point) cuts)))
  21446. (dolist (c (delq end cuts))
  21447. (fill-region-as-paragraph c end justify)
  21448. (setq end c))))
  21449. t)))
  21450. ;; Contents of `comment-block' type elements should be
  21451. ;; filled as plain text, but only if point is within block
  21452. ;; markers.
  21453. (comment-block
  21454. (let* ((case-fold-search t)
  21455. (beg (save-excursion
  21456. (goto-char (org-element-property :begin element))
  21457. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21458. (forward-line)
  21459. (point)))
  21460. (end (save-excursion
  21461. (goto-char (org-element-property :end element))
  21462. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21463. (line-beginning-position))))
  21464. (if (or (< (point) beg) (> (point) end)) t
  21465. (fill-region-as-paragraph
  21466. (save-excursion (end-of-line)
  21467. (re-search-backward "^[ \t]*$" beg 'move)
  21468. (line-beginning-position))
  21469. (save-excursion (beginning-of-line)
  21470. (re-search-forward "^[ \t]*$" end 'move)
  21471. (line-beginning-position))
  21472. justify))))
  21473. ;; Fill comments.
  21474. (comment
  21475. (let ((begin (org-element-property :post-affiliated element))
  21476. (end (org-element-property :end element)))
  21477. (when (and (>= (point) begin) (<= (point) end))
  21478. (let ((begin (save-excursion
  21479. (end-of-line)
  21480. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21481. (progn (forward-line) (point))
  21482. begin)))
  21483. (end (save-excursion
  21484. (end-of-line)
  21485. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21486. (1- (line-beginning-position))
  21487. (skip-chars-backward " \r\t\n")
  21488. (line-end-position)))))
  21489. ;; Do not fill comments when at a blank line.
  21490. (when (> end begin)
  21491. (let ((fill-prefix
  21492. (save-excursion
  21493. (beginning-of-line)
  21494. (looking-at "[ \t]*#")
  21495. (let ((comment-prefix (match-string 0)))
  21496. (goto-char (match-end 0))
  21497. (if (looking-at adaptive-fill-regexp)
  21498. (concat comment-prefix (match-string 0))
  21499. (concat comment-prefix " "))))))
  21500. (save-excursion
  21501. (fill-region-as-paragraph begin end justify))))))
  21502. t))
  21503. ;; Ignore every other element.
  21504. (otherwise t))))))
  21505. (defun org-auto-fill-function ()
  21506. "Auto-fill function."
  21507. ;; Check if auto-filling is meaningful.
  21508. (let ((fc (current-fill-column)))
  21509. (when (and fc (> (current-column) fc))
  21510. (let* ((fill-prefix (org-adaptive-fill-function))
  21511. ;; Enforce empty fill prefix, if required. Otherwise, it
  21512. ;; will be computed again.
  21513. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21514. (when fill-prefix (do-auto-fill))))))
  21515. (defun org-comment-line-break-function (&optional soft)
  21516. "Break line at point and indent, continuing comment if within one.
  21517. The inserted newline is marked hard if variable
  21518. `use-hard-newlines' is true, unless optional argument SOFT is
  21519. non-nil."
  21520. (if soft (insert-and-inherit ?\n) (newline 1))
  21521. (save-excursion (forward-char -1) (delete-horizontal-space))
  21522. (delete-horizontal-space)
  21523. (indent-to-left-margin)
  21524. (insert-before-markers-and-inherit fill-prefix))
  21525. ;;; Fixed Width Areas
  21526. (defun org-toggle-fixed-width ()
  21527. "Toggle fixed-width markup.
  21528. Add or remove fixed-width markup on current line, whenever it
  21529. makes sense. Return an error otherwise.
  21530. If a region is active and if it contains only fixed-width areas
  21531. or blank lines, remove all fixed-width markup in it. If the
  21532. region contains anything else, convert all non-fixed-width lines
  21533. to fixed-width ones.
  21534. Blank lines at the end of the region are ignored unless the
  21535. region only contains such lines."
  21536. (interactive)
  21537. (if (not (org-region-active-p))
  21538. ;; No region:
  21539. ;;
  21540. ;; Remove fixed width marker only in a fixed-with element.
  21541. ;;
  21542. ;; Add fixed width maker in paragraphs, in blank lines after
  21543. ;; elements or at the beginning of a headline or an inlinetask,
  21544. ;; and before any one-line elements (e.g., a clock).
  21545. (progn
  21546. (beginning-of-line)
  21547. (let* ((element (org-element-at-point))
  21548. (type (org-element-type element)))
  21549. (cond
  21550. ((and (eq type 'fixed-width)
  21551. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21552. (replace-match
  21553. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21554. ((and (memq type '(babel-call clock comment diary-sexp headline
  21555. horizontal-rule keyword paragraph
  21556. planning))
  21557. (<= (org-element-property :post-affiliated element) (point)))
  21558. (skip-chars-forward " \t")
  21559. (insert ": "))
  21560. ((and (org-looking-at-p "[ \t]*$")
  21561. (or (eq type 'inlinetask)
  21562. (save-excursion
  21563. (skip-chars-forward " \r\t\n")
  21564. (<= (org-element-property :end element) (point)))))
  21565. (delete-region (point) (line-end-position))
  21566. (org-indent-line)
  21567. (insert ": "))
  21568. (t (user-error "Cannot insert a fixed-width line here")))))
  21569. ;; Region active.
  21570. (let* ((begin (save-excursion
  21571. (goto-char (region-beginning))
  21572. (line-beginning-position)))
  21573. (end (copy-marker
  21574. (save-excursion
  21575. (goto-char (region-end))
  21576. (unless (eolp) (beginning-of-line))
  21577. (if (save-excursion (re-search-backward "\\S-" begin t))
  21578. (progn (skip-chars-backward " \r\t\n") (point))
  21579. (point)))))
  21580. (all-fixed-width-p
  21581. (catch 'not-all-p
  21582. (save-excursion
  21583. (goto-char begin)
  21584. (skip-chars-forward " \r\t\n")
  21585. (when (eobp) (throw 'not-all-p nil))
  21586. (while (< (point) end)
  21587. (let ((element (org-element-at-point)))
  21588. (if (eq (org-element-type element) 'fixed-width)
  21589. (goto-char (org-element-property :end element))
  21590. (throw 'not-all-p nil))))
  21591. t))))
  21592. (if all-fixed-width-p
  21593. (save-excursion
  21594. (goto-char begin)
  21595. (while (< (point) end)
  21596. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21597. (replace-match
  21598. "" nil nil nil
  21599. (if (= (line-end-position) (match-end 0)) 0 1)))
  21600. (forward-line)))
  21601. (let ((min-ind (point-max)))
  21602. ;; Find minimum indentation across all lines.
  21603. (save-excursion
  21604. (goto-char begin)
  21605. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21606. (setq min-ind 0)
  21607. (catch 'zerop
  21608. (while (< (point) end)
  21609. (unless (org-looking-at-p "[ \t]*$")
  21610. (let ((ind (org-get-indentation)))
  21611. (setq min-ind (min min-ind ind))
  21612. (when (zerop ind) (throw 'zerop t))))
  21613. (forward-line)))))
  21614. ;; Loop over all lines and add fixed-width markup everywhere
  21615. ;; but in fixed-width lines.
  21616. (save-excursion
  21617. (goto-char begin)
  21618. (while (< (point) end)
  21619. (cond
  21620. ((org-at-heading-p)
  21621. (insert ": ")
  21622. (forward-line)
  21623. (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
  21624. (insert ":")
  21625. (forward-line)))
  21626. ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
  21627. (let* ((element (org-element-at-point))
  21628. (element-end (org-element-property :end element)))
  21629. (if (eq (org-element-type element) 'fixed-width)
  21630. (progn (goto-char element-end)
  21631. (skip-chars-backward " \r\t\n")
  21632. (forward-line))
  21633. (let ((limit (min end element-end)))
  21634. (while (< (point) limit)
  21635. (org-move-to-column min-ind t)
  21636. (insert ": ")
  21637. (forward-line))))))
  21638. (t
  21639. (org-move-to-column min-ind t)
  21640. (insert ": ")
  21641. (forward-line)))))))
  21642. (set-marker end nil))))
  21643. ;;; Comments
  21644. ;; Org comments syntax is quite complex. It requires the entire line
  21645. ;; to be just a comment. Also, even with the right syntax at the
  21646. ;; beginning of line, some some elements (i.e. verse-block or
  21647. ;; example-block) don't accept comments. Usual Emacs comment commands
  21648. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21649. ;; Org still relies on `comment-dwim', but cannot trust
  21650. ;; `comment-only-p'. So, `comment-region-function' and
  21651. ;; `uncomment-region-function' both point
  21652. ;; to`org-comment-or-uncomment-region'. Eventually,
  21653. ;; `org-insert-comment' takes care of insertion of comments at the
  21654. ;; beginning of line.
  21655. ;; `org-setup-comments-handling' install comments related variables
  21656. ;; during `org-mode' initialization.
  21657. (defun org-setup-comments-handling ()
  21658. (interactive)
  21659. (setq-local comment-use-syntax nil)
  21660. (setq-local comment-start "# ")
  21661. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21662. (setq-local comment-insert-comment-function 'org-insert-comment)
  21663. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21664. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21665. (defun org-insert-comment ()
  21666. "Insert an empty comment above current line.
  21667. If the line is empty, insert comment at its beginning. When
  21668. point is within a source block, comment according to the related
  21669. major mode."
  21670. (if (let ((element (org-element-at-point)))
  21671. (and (eq (org-element-type element) 'src-block)
  21672. (< (save-excursion
  21673. (goto-char (org-element-property :post-affiliated element))
  21674. (line-end-position))
  21675. (point))
  21676. (> (save-excursion
  21677. (goto-char (org-element-property :end element))
  21678. (skip-chars-backward " \r\t\n")
  21679. (line-beginning-position))
  21680. (point))))
  21681. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21682. (beginning-of-line)
  21683. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21684. (open-line 1))
  21685. (org-indent-line)
  21686. (insert "# ")))
  21687. (defvar comment-empty-lines) ; From newcomment.el.
  21688. (defun org-comment-or-uncomment-region (beg end &rest _)
  21689. "Comment or uncomment each non-blank line in the region.
  21690. Uncomment each non-blank line between BEG and END if it only
  21691. contains commented lines. Otherwise, comment them. If region is
  21692. strictly within a source block, use appropriate comment syntax."
  21693. (if (let ((element (org-element-at-point)))
  21694. (and (eq (org-element-type element) 'src-block)
  21695. (< (save-excursion
  21696. (goto-char (org-element-property :post-affiliated element))
  21697. (line-end-position))
  21698. beg)
  21699. (>= (save-excursion
  21700. (goto-char (org-element-property :end element))
  21701. (skip-chars-backward " \r\t\n")
  21702. (line-beginning-position))
  21703. end)))
  21704. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21705. (save-restriction
  21706. ;; Restrict region
  21707. (narrow-to-region (save-excursion (goto-char beg)
  21708. (skip-chars-forward " \r\t\n" end)
  21709. (line-beginning-position))
  21710. (save-excursion (goto-char end)
  21711. (skip-chars-backward " \r\t\n" beg)
  21712. (line-end-position)))
  21713. (let ((uncommentp
  21714. ;; UNCOMMENTP is non-nil when every non blank line between
  21715. ;; BEG and END is a comment.
  21716. (save-excursion
  21717. (goto-char (point-min))
  21718. (while (and (not (eobp))
  21719. (let ((element (org-element-at-point)))
  21720. (and (eq (org-element-type element) 'comment)
  21721. (goto-char (min (point-max)
  21722. (org-element-property
  21723. :end element)))))))
  21724. (eobp))))
  21725. (if uncommentp
  21726. ;; Only blank lines and comments in region: uncomment it.
  21727. (save-excursion
  21728. (goto-char (point-min))
  21729. (while (not (eobp))
  21730. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21731. (replace-match "" nil nil nil 1))
  21732. (forward-line)))
  21733. ;; Comment each line in region.
  21734. (let ((min-indent (point-max)))
  21735. ;; First find the minimum indentation across all lines.
  21736. (save-excursion
  21737. (goto-char (point-min))
  21738. (while (and (not (eobp)) (not (zerop min-indent)))
  21739. (unless (looking-at "[ \t]*$")
  21740. (setq min-indent (min min-indent (current-indentation))))
  21741. (forward-line)))
  21742. ;; Then loop over all lines.
  21743. (save-excursion
  21744. (goto-char (point-min))
  21745. (while (not (eobp))
  21746. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21747. ;; Don't get fooled by invisible text (e.g. link path)
  21748. ;; when moving to column MIN-INDENT.
  21749. (let ((buffer-invisibility-spec nil))
  21750. (org-move-to-column min-indent t))
  21751. (insert comment-start))
  21752. (forward-line)))))))))
  21753. (defun org-comment-dwim (arg)
  21754. "Call `comment-dwim' within a source edit buffer if needed."
  21755. (interactive "*P")
  21756. (if (org-in-src-block-p)
  21757. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21758. (call-interactively 'comment-dwim)))
  21759. ;;; Timestamps API
  21760. ;; This section contains tools to operate on timestamp objects, as
  21761. ;; returned by, e.g. `org-element-context'.
  21762. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21763. "Encode TIMESTAMP object into Emacs internal time.
  21764. Use end of date range or time range when END is non-nil."
  21765. (apply #'encode-time
  21766. (cons 0
  21767. (mapcar
  21768. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21769. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21770. '(:minute-start :hour-start :day-start :month-start
  21771. :year-start))))))
  21772. (defun org-timestamp-has-time-p (timestamp)
  21773. "Non-nil when TIMESTAMP has a time specified."
  21774. (org-element-property :hour-start timestamp))
  21775. (defun org-timestamp-format (timestamp format &optional end utc)
  21776. "Format a TIMESTAMP object into a string.
  21777. FORMAT is a format specifier to be passed to
  21778. `format-time-string'.
  21779. When optional argument END is non-nil, use end of date-range or
  21780. time-range, if possible.
  21781. When optional argument UTC is non-nil, time will be expressed as
  21782. Universal Time."
  21783. (format-time-string
  21784. format (org-timestamp--to-internal-time timestamp end) utc))
  21785. (defun org-timestamp-split-range (timestamp &optional end)
  21786. "Extract a TIMESTAMP object from a date or time range.
  21787. END, when non-nil, means extract the end of the range.
  21788. Otherwise, extract its start.
  21789. Return a new timestamp object."
  21790. (let ((type (org-element-property :type timestamp)))
  21791. (if (memq type '(active inactive diary)) timestamp
  21792. (let ((split-ts (org-element-copy timestamp)))
  21793. ;; Set new type.
  21794. (org-element-put-property
  21795. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21796. ;; Copy start properties over end properties if END is
  21797. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21798. (let ((p-alist '((:minute-start . :minute-end)
  21799. (:hour-start . :hour-end)
  21800. (:day-start . :day-end)
  21801. (:month-start . :month-end)
  21802. (:year-start . :year-end))))
  21803. (dolist (p-cell p-alist)
  21804. (org-element-put-property
  21805. split-ts
  21806. (funcall (if end #'car #'cdr) p-cell)
  21807. (org-element-property
  21808. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21809. ;; Eventually refresh `:raw-value'.
  21810. (org-element-put-property split-ts :raw-value nil)
  21811. (org-element-put-property
  21812. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21813. (defun org-timestamp-translate (timestamp &optional boundary)
  21814. "Translate TIMESTAMP object to custom format.
  21815. Format string is defined in `org-time-stamp-custom-formats',
  21816. which see.
  21817. When optional argument BOUNDARY is non-nil, it is either the
  21818. symbol `start' or `end'. In this case, only translate the
  21819. starting or ending part of TIMESTAMP if it is a date or time
  21820. range. Otherwise, translate both parts.
  21821. Return timestamp as-is if `org-display-custom-times' is nil or if
  21822. it has a `diary' type."
  21823. (let ((type (org-element-property :type timestamp)))
  21824. (if (or (not org-display-custom-times) (eq type 'diary))
  21825. (org-element-interpret-data timestamp)
  21826. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21827. org-time-stamp-custom-formats)))
  21828. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21829. (concat (org-timestamp-format timestamp fmt)
  21830. "--"
  21831. (org-timestamp-format timestamp fmt t))
  21832. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21833. ;;; Other stuff.
  21834. (defvar reftex-docstruct-symbol)
  21835. (defvar reftex-cite-format)
  21836. (defvar org--rds)
  21837. (defun org-reftex-citation ()
  21838. "Use reftex-citation to insert a citation into the buffer.
  21839. This looks for a line like
  21840. #+BIBLIOGRAPHY: foo plain option:-d
  21841. and derives from it that foo.bib is the bibliography file relevant
  21842. for this document. It then installs the necessary environment for RefTeX
  21843. to work in this buffer and calls `reftex-citation' to insert a citation
  21844. into the buffer.
  21845. Export of such citations to both LaTeX and HTML is handled by the contributed
  21846. package ox-bibtex by Taru Karttunen."
  21847. (interactive)
  21848. (let ((reftex-docstruct-symbol 'org--rds)
  21849. (reftex-cite-format "\\cite{%l}")
  21850. org--rds bib)
  21851. (save-excursion
  21852. (save-restriction
  21853. (widen)
  21854. (let ((case-fold-search t)
  21855. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21856. (if (not (save-excursion
  21857. (or (re-search-forward re nil t)
  21858. (re-search-backward re nil t))))
  21859. (user-error "No bibliography defined in file")
  21860. (setq bib (concat (match-string 1) ".bib")
  21861. org--rds (list (list 'bib bib)))))))
  21862. (call-interactively 'reftex-citation)))
  21863. ;;;; Functions extending outline functionality
  21864. (defun org-beginning-of-line (&optional arg)
  21865. "Go to the beginning of the current line. If that is invisible, continue
  21866. to a visible line beginning. This makes the function of C-a more intuitive.
  21867. If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
  21868. first attempt, and only move to after the tags when the cursor is already
  21869. beyond the end of the headline."
  21870. (interactive "P")
  21871. (let ((pos (point))
  21872. (special (if (consp org-special-ctrl-a/e)
  21873. (car org-special-ctrl-a/e)
  21874. org-special-ctrl-a/e))
  21875. deactivate-mark refpos)
  21876. (if (org-bound-and-true-p visual-line-mode)
  21877. (beginning-of-visual-line 1)
  21878. (beginning-of-line 1))
  21879. (if (and arg (fboundp 'move-beginning-of-line))
  21880. (call-interactively 'move-beginning-of-line)
  21881. (unless (bobp)
  21882. (backward-char 1)
  21883. (if (org-truely-invisible-p)
  21884. (while (and (not (bobp)) (org-truely-invisible-p))
  21885. (backward-char 1)
  21886. (beginning-of-line 1))
  21887. (forward-char 1))))
  21888. (when special
  21889. (cond
  21890. ((and (looking-at org-complex-heading-regexp)
  21891. (eq (char-after (match-end 1)) ?\s))
  21892. (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21893. (point-at-eol)))
  21894. (goto-char
  21895. (if (eq special t)
  21896. (cond ((> pos refpos) refpos)
  21897. ((= pos (point)) refpos)
  21898. (t (point)))
  21899. (cond ((> pos (point)) (point))
  21900. ((not (eq last-command this-command)) (point))
  21901. (t refpos)))))
  21902. ((org-at-item-p)
  21903. ;; Being at an item and not looking at an the item means point
  21904. ;; was previously moved to beginning of a visual line, which
  21905. ;; doesn't contain the item. Therefore, do nothing special,
  21906. ;; just stay here.
  21907. (when (looking-at org-list-full-item-re)
  21908. ;; Set special position at first white space character after
  21909. ;; bullet, and check-box, if any.
  21910. (let ((after-bullet
  21911. (let ((box (match-end 3)))
  21912. (if (not box) (match-end 1)
  21913. (let ((after (char-after box)))
  21914. (if (and after (= after ? )) (1+ box) box))))))
  21915. ;; Special case: Move point to special position when
  21916. ;; currently after it or at beginning of line.
  21917. (if (eq special t)
  21918. (when (or (> pos after-bullet) (= (point) pos))
  21919. (goto-char after-bullet))
  21920. ;; Reversed case: Move point to special position when
  21921. ;; point was already at beginning of line and command is
  21922. ;; repeated.
  21923. (when (and (= (point) pos) (eq last-command this-command))
  21924. (goto-char after-bullet))))))))
  21925. (org-no-warnings
  21926. (and (featurep 'xemacs) (setq zmacs-region-stays t))))
  21927. (setq disable-point-adjustment
  21928. (or (not (invisible-p (point)))
  21929. (not (invisible-p (max (point-min) (1- (point))))))))
  21930. (defun org-end-of-line (&optional arg)
  21931. "Go to the end of the line.
  21932. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21933. tags on the first attempt, and only move to after the tags when
  21934. the cursor is already beyond the end of the headline."
  21935. (interactive "P")
  21936. (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
  21937. org-special-ctrl-a/e))
  21938. (move-fun (cond ((org-bound-and-true-p visual-line-mode)
  21939. 'end-of-visual-line)
  21940. ((fboundp 'move-end-of-line) 'move-end-of-line)
  21941. (t 'end-of-line)))
  21942. deactivate-mark)
  21943. (if (or (not special) arg) (call-interactively move-fun)
  21944. (let* ((element (save-excursion (beginning-of-line)
  21945. (org-element-at-point)))
  21946. (type (org-element-type element)))
  21947. (cond
  21948. ((memq type '(headline inlinetask))
  21949. (let ((pos (point)))
  21950. (beginning-of-line 1)
  21951. (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
  21952. (if (eq special t)
  21953. (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
  21954. (goto-char (match-beginning 1))
  21955. (goto-char (match-end 0)))
  21956. (if (or (< pos (match-end 0))
  21957. (not (eq this-command last-command)))
  21958. (goto-char (match-end 0))
  21959. (goto-char (match-beginning 1))))
  21960. (call-interactively move-fun))))
  21961. ((outline-invisible-p (line-end-position))
  21962. ;; If element is hidden, `move-end-of-line' would put point
  21963. ;; after it. Use `end-of-line' to stay on current line.
  21964. (call-interactively 'end-of-line))
  21965. (t (call-interactively move-fun)))))
  21966. (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
  21967. (setq disable-point-adjustment
  21968. (or (not (invisible-p (point)))
  21969. (not (invisible-p (max (point-min) (1- (point))))))))
  21970. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21971. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21972. (defun org-backward-sentence (&optional _arg)
  21973. "Go to beginning of sentence, or beginning of table field.
  21974. This will call `backward-sentence' or `org-table-beginning-of-field',
  21975. depending on context."
  21976. (interactive)
  21977. (let* ((element (org-element-at-point))
  21978. (contents-begin (org-element-property :contents-begin element))
  21979. (table (org-element-lineage element '(table) t)))
  21980. (if (and table
  21981. (> (point) contents-begin)
  21982. (<= (point) (org-element-property :contents-end table)))
  21983. (call-interactively #'org-table-beginning-of-field)
  21984. (save-restriction
  21985. (when (and contents-begin
  21986. (< (point-min) contents-begin)
  21987. (> (point) contents-begin))
  21988. (narrow-to-region contents-begin
  21989. (org-element-property :contents-end element)))
  21990. (call-interactively #'backward-sentence)))))
  21991. (defun org-forward-sentence (&optional _arg)
  21992. "Go to end of sentence, or end of table field.
  21993. This will call `forward-sentence' or `org-table-end-of-field',
  21994. depending on context."
  21995. (interactive)
  21996. (let* ((element (org-element-at-point))
  21997. (contents-end (org-element-property :contents-end element))
  21998. (table (org-element-lineage element '(table) t)))
  21999. (if (and table
  22000. (>= (point) (org-element-property :contents-begin table))
  22001. (< (point) contents-end))
  22002. (call-interactively #'org-table-end-of-field)
  22003. (save-restriction
  22004. (when (and contents-end
  22005. (> (point-max) contents-end)
  22006. ;; Skip blank lines between elements.
  22007. (< (org-element-property :end element)
  22008. (save-excursion (goto-char contents-end)
  22009. (skip-chars-forward " \r\t\n"))))
  22010. (narrow-to-region (org-element-property :contents-begin element)
  22011. contents-end))
  22012. (call-interactively #'forward-sentence)))))
  22013. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  22014. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  22015. (defun org-kill-line (&optional _arg)
  22016. "Kill line, to tags or end of line."
  22017. (interactive)
  22018. (cond
  22019. ((or (not org-special-ctrl-k)
  22020. (bolp)
  22021. (not (org-at-heading-p)))
  22022. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  22023. org-ctrl-k-protect-subtree
  22024. (or (eq org-ctrl-k-protect-subtree 'error)
  22025. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  22026. (user-error "C-k aborted as it would kill a hidden subtree"))
  22027. (call-interactively
  22028. (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  22029. ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
  22030. (kill-region (point) (match-beginning 1))
  22031. (org-set-tags nil t))
  22032. (t (kill-region (point) (point-at-eol)))))
  22033. (define-key org-mode-map "\C-k" 'org-kill-line)
  22034. (defun org-yank (&optional arg)
  22035. "Yank. If the kill is a subtree, treat it specially.
  22036. This command will look at the current kill and check if is a single
  22037. subtree, or a series of subtrees[1]. If it passes the test, and if the
  22038. cursor is at the beginning of a line or after the stars of a currently
  22039. empty headline, then the yank is handled specially. How exactly depends
  22040. on the value of the following variables, both set by default.
  22041. `org-yank-folded-subtrees'
  22042. When set, the subtree(s) will be folded after insertion, but only
  22043. if doing so would now swallow text after the yanked text.
  22044. `org-yank-adjusted-subtrees'
  22045. When set, the subtree will be promoted or demoted in order to
  22046. fit into the local outline tree structure, which means that the
  22047. level will be adjusted so that it becomes the smaller one of the
  22048. two *visible* surrounding headings.
  22049. Any prefix to this command will cause `yank' to be called directly with
  22050. no special treatment. In particular, a simple \\[universal-argument] prefix \
  22051. will just
  22052. plainly yank the text as it is.
  22053. \[1] The test checks if the first non-white line is a heading
  22054. and if there are no other headings with fewer stars."
  22055. (interactive "P")
  22056. (org-yank-generic 'yank arg))
  22057. (defun org-yank-generic (command arg)
  22058. "Perform some yank-like command.
  22059. This function implements the behavior described in the `org-yank'
  22060. documentation. However, it has been generalized to work for any
  22061. interactive command with similar behavior."
  22062. ;; pretend to be command COMMAND
  22063. (setq this-command command)
  22064. (if arg
  22065. (call-interactively command)
  22066. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  22067. (and (org-kill-is-subtree-p)
  22068. (or (bolp)
  22069. (and (looking-at "[ \t]*$")
  22070. (string-match
  22071. "\\`\\*+\\'"
  22072. (buffer-substring (point-at-bol) (point)))))))
  22073. swallowp)
  22074. (cond
  22075. ((and subtreep org-yank-folded-subtrees)
  22076. (let ((beg (point))
  22077. end)
  22078. (if (and subtreep org-yank-adjusted-subtrees)
  22079. (org-paste-subtree nil nil 'for-yank)
  22080. (call-interactively command))
  22081. (setq end (point))
  22082. (goto-char beg)
  22083. (when (and (bolp) subtreep
  22084. (not (setq swallowp
  22085. (org-yank-folding-would-swallow-text beg end))))
  22086. (org-with-limited-levels
  22087. (or (looking-at org-outline-regexp)
  22088. (re-search-forward org-outline-regexp-bol end t))
  22089. (while (and (< (point) end) (looking-at org-outline-regexp))
  22090. (outline-hide-subtree)
  22091. (org-cycle-show-empty-lines 'folded)
  22092. (condition-case nil
  22093. (outline-forward-same-level 1)
  22094. (error (goto-char end))))))
  22095. (when swallowp
  22096. (message
  22097. "Inserted text not folded because that would swallow text"))
  22098. (goto-char end)
  22099. (skip-chars-forward " \t\n\r")
  22100. (beginning-of-line 1)
  22101. (push-mark beg 'nomsg)))
  22102. ((and subtreep org-yank-adjusted-subtrees)
  22103. (let ((beg (point-at-bol)))
  22104. (org-paste-subtree nil nil 'for-yank)
  22105. (push-mark beg 'nomsg)))
  22106. (t
  22107. (call-interactively command))))))
  22108. (defun org-yank-folding-would-swallow-text (beg end)
  22109. "Would hide-subtree at BEG swallow any text after END?"
  22110. (let (level)
  22111. (org-with-limited-levels
  22112. (save-excursion
  22113. (goto-char beg)
  22114. (when (or (looking-at org-outline-regexp)
  22115. (re-search-forward org-outline-regexp-bol end t))
  22116. (setq level (org-outline-level)))
  22117. (goto-char end)
  22118. (skip-chars-forward " \t\r\n\v\f")
  22119. (not (or (eobp)
  22120. (and (bolp) (looking-at-p org-outline-regexp)
  22121. (<= (org-outline-level) level))))))))
  22122. (define-key org-mode-map "\C-y" 'org-yank)
  22123. (defun org-truely-invisible-p ()
  22124. "Check if point is at a character currently not visible.
  22125. This version does not only check the character property, but also
  22126. `visible-mode'."
  22127. ;; Early versions of noutline don't have `outline-invisible-p'.
  22128. (unless (org-bound-and-true-p visible-mode)
  22129. (outline-invisible-p)))
  22130. (defun org-invisible-p2 ()
  22131. "Check if point is at a character currently not visible."
  22132. (save-excursion
  22133. (when (and (eolp) (not (bobp))) (backward-char 1))
  22134. ;; Early versions of noutline don't have `outline-invisible-p'.
  22135. (outline-invisible-p)))
  22136. (defun org-back-to-heading (&optional invisible-ok)
  22137. "Call `outline-back-to-heading', but provide a better error message."
  22138. (condition-case nil
  22139. (outline-back-to-heading invisible-ok)
  22140. (error (error "Before first headline at position %d in buffer %s"
  22141. (point) (current-buffer)))))
  22142. (defun org-before-first-heading-p ()
  22143. "Before first heading?"
  22144. (save-excursion
  22145. (end-of-line)
  22146. (null (re-search-backward org-outline-regexp-bol nil t))))
  22147. (defun org-at-heading-p (&optional ignored)
  22148. (outline-on-heading-p t))
  22149. ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
  22150. ;;; warning was only added in Org 9.0, which should be taken into
  22151. ;;; account when deciding when to remove the alias.
  22152. (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
  22153. (defun org-in-commented-heading-p (&optional no-inheritance)
  22154. "Non-nil if point is under a commented heading.
  22155. This function also checks ancestors of the current headline,
  22156. unless optional argument NO-INHERITANCE is non-nil."
  22157. (cond
  22158. ((org-before-first-heading-p) nil)
  22159. ((let ((headline (nth 4 (org-heading-components))))
  22160. (and headline
  22161. (let ((case-fold-search nil))
  22162. (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22163. headline)))))
  22164. (no-inheritance nil)
  22165. (t
  22166. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22167. (defun org-at-comment-p nil
  22168. "Is cursor in a commented line?"
  22169. (save-excursion
  22170. (save-match-data
  22171. (beginning-of-line)
  22172. (looking-at "^[ \t]*# "))))
  22173. (defun org-at-drawer-p nil
  22174. "Is cursor at a drawer keyword?"
  22175. (save-excursion
  22176. (move-beginning-of-line 1)
  22177. (looking-at org-drawer-regexp)))
  22178. (defun org-at-block-p nil
  22179. "Is cursor at a block keyword?"
  22180. (save-excursion
  22181. (move-beginning-of-line 1)
  22182. (looking-at org-block-regexp)))
  22183. (defun org-point-at-end-of-empty-headline ()
  22184. "If point is at the end of an empty headline, return t, else nil.
  22185. If the heading only contains a TODO keyword, it is still still considered
  22186. empty."
  22187. (and (looking-at "[ \t]*$")
  22188. (when org-todo-line-regexp
  22189. (save-excursion
  22190. (beginning-of-line 1)
  22191. (let ((case-fold-search nil))
  22192. (looking-at org-todo-line-regexp)
  22193. (string= (match-string 3) ""))))))
  22194. (defun org-at-heading-or-item-p ()
  22195. (or (org-at-heading-p) (org-at-item-p)))
  22196. (defun org-at-target-p ()
  22197. (or (org-in-regexp org-radio-target-regexp)
  22198. (org-in-regexp org-target-regexp)))
  22199. ;; Compatibility alias with Org versions < 7.8.03
  22200. (defalias 'org-on-target-p 'org-at-target-p)
  22201. (defun org-up-heading-all (arg)
  22202. "Move to the heading line of which the present line is a subheading.
  22203. This function considers both visible and invisible heading lines.
  22204. With argument, move up ARG levels."
  22205. (if (fboundp 'outline-up-heading-all)
  22206. (outline-up-heading-all arg) ; emacs 21 version of outline.el
  22207. (outline-up-heading arg t))) ; emacs 22 version of outline.el
  22208. (defun org-up-heading-safe ()
  22209. "Move to the heading line of which the present line is a subheading.
  22210. This version will not throw an error. It will return the level of the
  22211. headline found, or nil if no higher level is found.
  22212. Also, this function will be a lot faster than `outline-up-heading',
  22213. because it relies on stars being the outline starters. This can really
  22214. make a significant difference in outlines with very many siblings."
  22215. (when (ignore-errors (org-back-to-heading t))
  22216. (let ((level-up (1- (funcall outline-level))))
  22217. (and (> level-up 0)
  22218. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22219. (funcall outline-level)))))
  22220. (defun org-first-sibling-p ()
  22221. "Is this heading the first child of its parents?"
  22222. (interactive)
  22223. (let ((re org-outline-regexp-bol)
  22224. level l)
  22225. (unless (org-at-heading-p t)
  22226. (user-error "Not at a heading"))
  22227. (setq level (funcall outline-level))
  22228. (save-excursion
  22229. (if (not (re-search-backward re nil t))
  22230. t
  22231. (setq l (funcall outline-level))
  22232. (< l level)))))
  22233. (defun org-goto-sibling (&optional previous)
  22234. "Goto the next sibling, even if it is invisible.
  22235. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22236. when a sibling was found. When none is found, return nil and don't
  22237. move point."
  22238. (let ((fun (if previous 're-search-backward 're-search-forward))
  22239. (pos (point))
  22240. (re org-outline-regexp-bol)
  22241. level l)
  22242. (when (ignore-errors (org-back-to-heading t))
  22243. (setq level (funcall outline-level))
  22244. (catch 'exit
  22245. (or previous (forward-char 1))
  22246. (while (funcall fun re nil t)
  22247. (setq l (funcall outline-level))
  22248. (when (< l level) (goto-char pos) (throw 'exit nil))
  22249. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22250. (goto-char pos)
  22251. nil))))
  22252. (defun org-show-siblings ()
  22253. "Show all siblings of the current headline."
  22254. (save-excursion
  22255. (while (org-goto-sibling) (org-flag-heading nil)))
  22256. (save-excursion
  22257. (while (org-goto-sibling 'previous)
  22258. (org-flag-heading nil))))
  22259. (defun org-goto-first-child ()
  22260. "Goto the first child, even if it is invisible.
  22261. Return t when a child was found. Otherwise don't move point and
  22262. return nil."
  22263. (let (level (pos (point)) (re org-outline-regexp-bol))
  22264. (when (ignore-errors (org-back-to-heading t))
  22265. (setq level (outline-level))
  22266. (forward-char 1)
  22267. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22268. (progn (goto-char (match-beginning 0)) t)
  22269. (goto-char pos) nil))))
  22270. (defun org-show-hidden-entry ()
  22271. "Show an entry where even the heading is hidden."
  22272. (save-excursion
  22273. (org-show-entry)))
  22274. (defun org-flag-heading (flag &optional entry)
  22275. "Flag the current heading. FLAG non-nil means make invisible.
  22276. When ENTRY is non-nil, show the entire entry."
  22277. (save-excursion
  22278. (org-back-to-heading t)
  22279. ;; Check if we should show the entire entry
  22280. (if entry
  22281. (progn
  22282. (org-show-entry)
  22283. (save-excursion
  22284. (and (outline-next-heading)
  22285. (org-flag-heading nil))))
  22286. (outline-flag-region (max (point-min) (1- (point)))
  22287. (save-excursion (outline-end-of-heading) (point))
  22288. flag))))
  22289. (defun org-get-next-sibling ()
  22290. "Move to next heading of the same level, and return point.
  22291. If there is no such heading, return nil.
  22292. This is like outline-next-sibling, but invisible headings are ok."
  22293. (let ((level (funcall outline-level)))
  22294. (outline-next-heading)
  22295. (while (and (not (eobp)) (> (funcall outline-level) level))
  22296. (outline-next-heading))
  22297. (unless (or (eobp) (< (funcall outline-level) level))
  22298. (point))))
  22299. (defun org-get-last-sibling ()
  22300. "Move to previous heading of the same level, and return point.
  22301. If there is no such heading, return nil."
  22302. (let ((opoint (point))
  22303. (level (funcall outline-level)))
  22304. (outline-previous-heading)
  22305. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22306. (while (and (> (funcall outline-level) level)
  22307. (not (bobp)))
  22308. (outline-previous-heading))
  22309. (unless (< (funcall outline-level) level)
  22310. (point)))))
  22311. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22312. "Goto to the end of a subtree."
  22313. ;; This contains an exact copy of the original function, but it uses
  22314. ;; `org-back-to-heading', to make it work also in invisible
  22315. ;; trees. And is uses an invisible-ok argument.
  22316. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22317. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22318. ;; with many children and grandchildren etc, this can be much faster
  22319. ;; than the outline version.
  22320. (org-back-to-heading invisible-ok)
  22321. (let ((first t)
  22322. (level (funcall outline-level)))
  22323. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22324. ;; A true heading (not a plain list item), in Org-mode
  22325. ;; This means we can easily find the end by looking
  22326. ;; only for the right number of stars. Using a regexp to do
  22327. ;; this is so much faster than using a Lisp loop.
  22328. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22329. (forward-char 1)
  22330. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22331. ;; something else, do it the slow way
  22332. (while (and (not (eobp))
  22333. (or first (> (funcall outline-level) level)))
  22334. (setq first nil)
  22335. (outline-next-heading)))
  22336. (unless to-heading
  22337. (when (memq (preceding-char) '(?\n ?\^M))
  22338. ;; Go to end of line before heading
  22339. (forward-char -1)
  22340. (when (memq (preceding-char) '(?\n ?\^M))
  22341. ;; leave blank line before heading
  22342. (forward-char -1)))))
  22343. (point))
  22344. (defun org-end-of-meta-data (&optional full)
  22345. "Skip planning line and properties drawer in current entry.
  22346. When optional argument FULL is non-nil, also skip empty lines,
  22347. clocking lines and regular drawers at the beginning of the
  22348. entry."
  22349. (org-back-to-heading t)
  22350. (forward-line)
  22351. (when (org-looking-at-p org-planning-line-re) (forward-line))
  22352. (when (looking-at org-property-drawer-re)
  22353. (goto-char (match-end 0))
  22354. (forward-line))
  22355. (when (and full (not (org-at-heading-p)))
  22356. (catch 'exit
  22357. (let ((end (save-excursion (outline-next-heading) (point)))
  22358. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22359. (while (not (eobp))
  22360. (cond ((org-looking-at-p org-drawer-regexp)
  22361. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22362. (forward-line)
  22363. (throw 'exit t)))
  22364. ((org-looking-at-p re) (forward-line))
  22365. (t (throw 'exit t))))))))
  22366. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22367. "Move forward to the ARG'th subheading at same level as this one.
  22368. Stop at the first and last subheadings of a superior heading.
  22369. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22370. non-nil it will also look at invisible ones."
  22371. (interactive "p")
  22372. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22373. (if (and arg (< arg 0))
  22374. (goto-char (point-min))
  22375. (outline-next-heading))
  22376. (org-at-heading-p)
  22377. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22378. (f (if (and arg (< arg 0))
  22379. 're-search-backward
  22380. 're-search-forward))
  22381. (count (if arg (abs arg) 1))
  22382. (result (point)))
  22383. (while (and (prog1 (> count 0)
  22384. (forward-char (if (and arg (< arg 0)) -1 1)))
  22385. (funcall f org-outline-regexp-bol nil 'move))
  22386. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22387. (cond ((< l level) (setq count 0))
  22388. ((and (= l level)
  22389. (or invisible-ok
  22390. (progn
  22391. (goto-char (line-beginning-position))
  22392. (not (outline-invisible-p)))))
  22393. (setq count (1- count))
  22394. (when (eq l level)
  22395. (setq result (point)))))))
  22396. (goto-char result))
  22397. (beginning-of-line 1)))
  22398. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22399. "Move backward to the ARG'th subheading at same level as this one.
  22400. Stop at the first and last subheadings of a superior heading."
  22401. (interactive "p")
  22402. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22403. (defun org-next-visible-heading (arg)
  22404. "Move to the next visible heading.
  22405. This function wraps `outline-next-visible-heading' with
  22406. `org-with-limited-levels' in order to skip over inline tasks and
  22407. respect customization of `org-odd-levels-only'."
  22408. (interactive "p")
  22409. (org-with-limited-levels
  22410. (outline-next-visible-heading arg)))
  22411. (defun org-previous-visible-heading (arg)
  22412. "Move to the next visible heading.
  22413. This function wraps `outline-previous-visible-heading' with
  22414. `org-with-limited-levels' in order to skip over inline tasks and
  22415. respect customization of `org-odd-levels-only'."
  22416. (interactive "p")
  22417. (org-with-limited-levels
  22418. (outline-previous-visible-heading arg)))
  22419. (defun org-next-block (arg &optional backward block-regexp)
  22420. "Jump to the next block.
  22421. With a prefix argument ARG, jump forward ARG many blocks.
  22422. When BACKWARD is non-nil, jump to the previous block.
  22423. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22424. Match data is set according to this regexp when the function
  22425. returns.
  22426. Return point at beginning of the opening line of found block.
  22427. Throw an error if no block is found."
  22428. (interactive "p")
  22429. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22430. (case-fold-search t)
  22431. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22432. (count (or arg 1))
  22433. (origin (point))
  22434. last-element)
  22435. (if backward (beginning-of-line) (end-of-line))
  22436. (while (and (> count 0) (funcall search-fn re nil t))
  22437. (let ((element (save-excursion
  22438. (goto-char (match-beginning 0))
  22439. (save-match-data (org-element-at-point)))))
  22440. (when (and (memq (org-element-type element)
  22441. '(center-block comment-block dynamic-block
  22442. example-block export-block quote-block
  22443. special-block src-block verse-block))
  22444. (<= (match-beginning 0)
  22445. (org-element-property :post-affiliated element)))
  22446. (setq last-element element)
  22447. (decf count))))
  22448. (if (= count 0)
  22449. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22450. (save-match-data (org-show-context)))
  22451. (goto-char origin)
  22452. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22453. (defun org-previous-block (arg &optional block-regexp)
  22454. "Jump to the previous block.
  22455. With a prefix argument ARG, jump backward ARG many source blocks.
  22456. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22457. (interactive "p")
  22458. (org-next-block arg t block-regexp))
  22459. (defun org-forward-paragraph ()
  22460. "Move forward to beginning of next paragraph or equivalent.
  22461. The function moves point to the beginning of the next visible
  22462. structural element, which can be a paragraph, a table, a list
  22463. item, etc. It also provides some special moves for convenience:
  22464. - On an affiliated keyword, jump to the beginning of the
  22465. relative element.
  22466. - On an item or a footnote definition, move to the second
  22467. element inside, if any.
  22468. - On a table or a property drawer, jump after it.
  22469. - On a verse or source block, stop after blank lines."
  22470. (interactive)
  22471. (when (eobp) (user-error "Cannot move further down"))
  22472. (let* ((deactivate-mark nil)
  22473. (element (org-element-at-point))
  22474. (type (org-element-type element))
  22475. (post-affiliated (org-element-property :post-affiliated element))
  22476. (contents-begin (org-element-property :contents-begin element))
  22477. (contents-end (org-element-property :contents-end element))
  22478. (end (let ((end (org-element-property :end element)) (parent element))
  22479. (while (and (setq parent (org-element-property :parent parent))
  22480. (= (org-element-property :contents-end parent) end))
  22481. (setq end (org-element-property :end parent)))
  22482. end)))
  22483. (cond ((not element)
  22484. (skip-chars-forward " \r\t\n")
  22485. (or (eobp) (beginning-of-line)))
  22486. ;; On affiliated keywords, move to element's beginning.
  22487. ((< (point) post-affiliated)
  22488. (goto-char post-affiliated))
  22489. ;; At a table row, move to the end of the table. Similarly,
  22490. ;; at a node property, move to the end of the property
  22491. ;; drawer.
  22492. ((memq type '(node-property table-row))
  22493. (goto-char (org-element-property
  22494. :end (org-element-property :parent element))))
  22495. ((memq type '(property-drawer table)) (goto-char end))
  22496. ;; Consider blank lines as separators in verse and source
  22497. ;; blocks to ease editing.
  22498. ((memq type '(src-block verse-block))
  22499. (when (eq type 'src-block)
  22500. (setq contents-end
  22501. (save-excursion (goto-char end)
  22502. (skip-chars-backward " \r\t\n")
  22503. (line-beginning-position))))
  22504. (beginning-of-line)
  22505. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22506. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22507. (goto-char end)
  22508. (skip-chars-forward " \r\t\n")
  22509. (if (= (point) contents-end) (goto-char end)
  22510. (beginning-of-line))))
  22511. ;; With no contents, just skip element.
  22512. ((not contents-begin) (goto-char end))
  22513. ;; If contents are invisible, skip the element altogether.
  22514. ((outline-invisible-p (line-end-position))
  22515. (case type
  22516. (headline
  22517. (org-with-limited-levels (outline-next-visible-heading 1)))
  22518. ;; At a plain list, make sure we move to the next item
  22519. ;; instead of skipping the whole list.
  22520. (plain-list (forward-char)
  22521. (org-forward-paragraph))
  22522. (otherwise (goto-char end))))
  22523. ((>= (point) contents-end) (goto-char end))
  22524. ((>= (point) contents-begin)
  22525. ;; This can only happen on paragraphs and plain lists.
  22526. (case type
  22527. (paragraph (goto-char end))
  22528. ;; At a plain list, try to move to second element in
  22529. ;; first item, if possible.
  22530. (plain-list (end-of-line)
  22531. (org-forward-paragraph))))
  22532. ;; When contents start on the middle of a line (e.g. in
  22533. ;; items and footnote definitions), try to reach first
  22534. ;; element starting after current line.
  22535. ((> (line-end-position) contents-begin)
  22536. (end-of-line)
  22537. (org-forward-paragraph))
  22538. (t (goto-char contents-begin)))))
  22539. (defun org-backward-paragraph ()
  22540. "Move backward to start of previous paragraph or equivalent.
  22541. The function moves point to the beginning of the current
  22542. structural element, which can be a paragraph, a table, a list
  22543. item, etc., or to the beginning of the previous visible one if
  22544. point is already there. It also provides some special moves for
  22545. convenience:
  22546. - On an affiliated keyword, jump to the first one.
  22547. - On a table or a property drawer, move to its beginning.
  22548. - On a verse or source block, stop before blank lines."
  22549. (interactive)
  22550. (when (bobp) (user-error "Cannot move further up"))
  22551. (let* ((deactivate-mark nil)
  22552. (element (org-element-at-point))
  22553. (type (org-element-type element))
  22554. (contents-begin (org-element-property :contents-begin element))
  22555. (contents-end (org-element-property :contents-end element))
  22556. (post-affiliated (org-element-property :post-affiliated element))
  22557. (begin (org-element-property :begin element)))
  22558. (cond
  22559. ((not element) (goto-char (point-min)))
  22560. ((= (point) begin)
  22561. (backward-char)
  22562. (org-backward-paragraph))
  22563. ((<= (point) post-affiliated) (goto-char begin))
  22564. ((memq type '(node-property table-row))
  22565. (goto-char (org-element-property
  22566. :post-affiliated (org-element-property :parent element))))
  22567. ((memq type '(property-drawer table)) (goto-char begin))
  22568. ((memq type '(src-block verse-block))
  22569. (when (eq type 'src-block)
  22570. (setq contents-begin
  22571. (save-excursion (goto-char begin) (forward-line) (point))))
  22572. (if (= (point) contents-begin) (goto-char post-affiliated)
  22573. ;; Inside a verse block, see blank lines as paragraph
  22574. ;; separators.
  22575. (let ((origin (point)))
  22576. (skip-chars-backward " \r\t\n" contents-begin)
  22577. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22578. (skip-chars-forward " \r\t\n" origin)
  22579. (if (= (point) origin) (goto-char contents-begin)
  22580. (beginning-of-line))))))
  22581. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22582. ((eq type 'paragraph)
  22583. (goto-char contents-begin)
  22584. ;; When at first paragraph in an item or a footnote definition,
  22585. ;; move directly to beginning of line.
  22586. (let ((parent-contents
  22587. (org-element-property
  22588. :contents-begin (org-element-property :parent element))))
  22589. (when (and parent-contents (= parent-contents contents-begin))
  22590. (beginning-of-line))))
  22591. ;; At the end of a greater element, move to the beginning of the
  22592. ;; last element within.
  22593. ((>= (point) contents-end)
  22594. (goto-char (1- contents-end))
  22595. (org-backward-paragraph))
  22596. (t (goto-char (or post-affiliated begin))))
  22597. ;; Ensure we never leave point invisible.
  22598. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22599. (defun org-forward-element ()
  22600. "Move forward by one element.
  22601. Move to the next element at the same level, when possible."
  22602. (interactive)
  22603. (cond ((eobp) (user-error "Cannot move further down"))
  22604. ((org-with-limited-levels (org-at-heading-p))
  22605. (let ((origin (point)))
  22606. (goto-char (org-end-of-subtree nil t))
  22607. (unless (org-with-limited-levels (org-at-heading-p))
  22608. (goto-char origin)
  22609. (user-error "Cannot move further down"))))
  22610. (t
  22611. (let* ((elem (org-element-at-point))
  22612. (end (org-element-property :end elem))
  22613. (parent (org-element-property :parent elem)))
  22614. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22615. (goto-char (org-element-property :end parent)))
  22616. ((integer-or-marker-p end) (goto-char end))
  22617. (t (message "No element at point")))))))
  22618. (defun org-backward-element ()
  22619. "Move backward by one element.
  22620. Move to the previous element at the same level, when possible."
  22621. (interactive)
  22622. (cond ((bobp) (user-error "Cannot move further up"))
  22623. ((org-with-limited-levels (org-at-heading-p))
  22624. ;; At a headline, move to the previous one, if any, or stay
  22625. ;; here.
  22626. (let ((origin (point)))
  22627. (org-with-limited-levels (org-backward-heading-same-level 1))
  22628. ;; When current headline has no sibling above, move to its
  22629. ;; parent.
  22630. (when (= (point) origin)
  22631. (or (org-with-limited-levels (org-up-heading-safe))
  22632. (progn (goto-char origin)
  22633. (user-error "Cannot move further up"))))))
  22634. (t
  22635. (let* ((elem (org-element-at-point))
  22636. (beg (org-element-property :begin elem)))
  22637. (cond
  22638. ;; Move to beginning of current element if point isn't
  22639. ;; there already.
  22640. ((null beg) (message "No element at point"))
  22641. ((/= (point) beg) (goto-char beg))
  22642. (t (goto-char beg)
  22643. (skip-chars-backward " \r\t\n")
  22644. (unless (bobp)
  22645. (let ((prev (org-element-at-point)))
  22646. (goto-char (org-element-property :begin prev))
  22647. (while (and (setq prev (org-element-property :parent prev))
  22648. (<= (org-element-property :end prev) beg))
  22649. (goto-char (org-element-property :begin prev)))))))))))
  22650. (defun org-up-element ()
  22651. "Move to upper element."
  22652. (interactive)
  22653. (if (org-with-limited-levels (org-at-heading-p))
  22654. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22655. (let* ((elem (org-element-at-point))
  22656. (parent (org-element-property :parent elem)))
  22657. (if parent (goto-char (org-element-property :begin parent))
  22658. (if (org-with-limited-levels (org-before-first-heading-p))
  22659. (user-error "No surrounding element")
  22660. (org-with-limited-levels (org-back-to-heading)))))))
  22661. (defvar org-element-greater-elements)
  22662. (defun org-down-element ()
  22663. "Move to inner element."
  22664. (interactive)
  22665. (let ((element (org-element-at-point)))
  22666. (cond
  22667. ((memq (org-element-type element) '(plain-list table))
  22668. (goto-char (org-element-property :contents-begin element))
  22669. (forward-char))
  22670. ((memq (org-element-type element) org-element-greater-elements)
  22671. ;; If contents are hidden, first disclose them.
  22672. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22673. (goto-char (or (org-element-property :contents-begin element)
  22674. (user-error "No content for this element"))))
  22675. (t (user-error "No inner element")))))
  22676. (defun org-drag-element-backward ()
  22677. "Move backward element at point."
  22678. (interactive)
  22679. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22680. (let* ((elem (org-element-at-point))
  22681. (prev-elem
  22682. (save-excursion
  22683. (goto-char (org-element-property :begin elem))
  22684. (skip-chars-backward " \r\t\n")
  22685. (unless (bobp)
  22686. (let* ((beg (org-element-property :begin elem))
  22687. (prev (org-element-at-point))
  22688. (up prev))
  22689. (while (and (setq up (org-element-property :parent up))
  22690. (<= (org-element-property :end up) beg))
  22691. (setq prev up))
  22692. prev)))))
  22693. ;; Error out if no previous element or previous element is
  22694. ;; a parent of the current one.
  22695. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22696. (user-error "Cannot drag element backward")
  22697. (let ((pos (point)))
  22698. (org-element-swap-A-B prev-elem elem)
  22699. (goto-char (+ (org-element-property :begin prev-elem)
  22700. (- pos (org-element-property :begin elem)))))))))
  22701. (defun org-drag-element-forward ()
  22702. "Move forward element at point."
  22703. (interactive)
  22704. (let* ((pos (point))
  22705. (elem (org-element-at-point)))
  22706. (when (= (point-max) (org-element-property :end elem))
  22707. (user-error "Cannot drag element forward"))
  22708. (goto-char (org-element-property :end elem))
  22709. (let ((next-elem (org-element-at-point)))
  22710. (when (or (org-element-nested-p elem next-elem)
  22711. (and (eq (org-element-type next-elem) 'headline)
  22712. (not (eq (org-element-type elem) 'headline))))
  22713. (goto-char pos)
  22714. (user-error "Cannot drag element forward"))
  22715. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22716. ;; body's length (without final blanks) and by the length of
  22717. ;; blanks between ELEM and NEXT-ELEM.
  22718. (let ((size-next (- (save-excursion
  22719. (goto-char (org-element-property :end next-elem))
  22720. (skip-chars-backward " \r\t\n")
  22721. (forward-line)
  22722. ;; Small correction if buffer doesn't end
  22723. ;; with a newline character.
  22724. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22725. (org-element-property :begin next-elem)))
  22726. (size-blank (- (org-element-property :end elem)
  22727. (save-excursion
  22728. (goto-char (org-element-property :end elem))
  22729. (skip-chars-backward " \r\t\n")
  22730. (forward-line)
  22731. (point)))))
  22732. (org-element-swap-A-B elem next-elem)
  22733. (goto-char (+ pos size-next size-blank))))))
  22734. (defun org-drag-line-forward (arg)
  22735. "Drag the line at point ARG lines forward."
  22736. (interactive "p")
  22737. (dotimes (n (abs arg))
  22738. (let ((c (current-column)))
  22739. (if (< 0 arg)
  22740. (progn
  22741. (beginning-of-line 2)
  22742. (transpose-lines 1)
  22743. (beginning-of-line 0))
  22744. (transpose-lines 1)
  22745. (beginning-of-line -1))
  22746. (org-move-to-column c))))
  22747. (defun org-drag-line-backward (arg)
  22748. "Drag the line at point ARG lines backward."
  22749. (interactive "p")
  22750. (org-drag-line-forward (- arg)))
  22751. (defun org-mark-element ()
  22752. "Put point at beginning of this element, mark at end.
  22753. Interactively, if this command is repeated or (in Transient Mark
  22754. mode) if the mark is active, it marks the next element after the
  22755. ones already marked."
  22756. (interactive)
  22757. (let (deactivate-mark)
  22758. (if (and (org-called-interactively-p 'any)
  22759. (or (and (eq last-command this-command) (mark t))
  22760. (and transient-mark-mode mark-active)))
  22761. (set-mark
  22762. (save-excursion
  22763. (goto-char (mark))
  22764. (goto-char (org-element-property :end (org-element-at-point)))))
  22765. (let ((element (org-element-at-point)))
  22766. (end-of-line)
  22767. (push-mark (org-element-property :end element) t t)
  22768. (goto-char (org-element-property :begin element))))))
  22769. (defun org-narrow-to-element ()
  22770. "Narrow buffer to current element."
  22771. (interactive)
  22772. (let ((elem (org-element-at-point)))
  22773. (cond
  22774. ((eq (car elem) 'headline)
  22775. (narrow-to-region
  22776. (org-element-property :begin elem)
  22777. (org-element-property :end elem)))
  22778. ((memq (car elem) org-element-greater-elements)
  22779. (narrow-to-region
  22780. (org-element-property :contents-begin elem)
  22781. (org-element-property :contents-end elem)))
  22782. (t
  22783. (narrow-to-region
  22784. (org-element-property :begin elem)
  22785. (org-element-property :end elem))))))
  22786. (defun org-transpose-element ()
  22787. "Transpose current and previous elements, keeping blank lines between.
  22788. Point is moved after both elements."
  22789. (interactive)
  22790. (org-skip-whitespace)
  22791. (let ((end (org-element-property :end (org-element-at-point))))
  22792. (org-drag-element-backward)
  22793. (goto-char end)))
  22794. (defun org-unindent-buffer ()
  22795. "Un-indent the visible part of the buffer.
  22796. Relative indentation (between items, inside blocks, etc.) isn't
  22797. modified."
  22798. (interactive)
  22799. (unless (eq major-mode 'org-mode)
  22800. (user-error "Cannot un-indent a buffer not in Org mode"))
  22801. (let* ((parse-tree (org-element-parse-buffer 'greater-element))
  22802. unindent-tree ; For byte-compiler.
  22803. (unindent-tree
  22804. (function
  22805. (lambda (contents)
  22806. (mapc
  22807. (lambda (element)
  22808. (if (memq (org-element-type element) '(headline section))
  22809. (funcall unindent-tree (org-element-contents element))
  22810. (save-excursion
  22811. (save-restriction
  22812. (narrow-to-region
  22813. (org-element-property :begin element)
  22814. (org-element-property :end element))
  22815. (org-do-remove-indentation)))))
  22816. (reverse contents))))))
  22817. (funcall unindent-tree (org-element-contents parse-tree))))
  22818. (defun org-show-children (&optional level)
  22819. "Show all direct subheadings of this heading.
  22820. Prefix arg LEVEL is how many levels below the current level
  22821. should be shown. Default is enough to cause the following
  22822. heading to appear."
  22823. (interactive "p")
  22824. (save-excursion
  22825. (org-back-to-heading t)
  22826. (let* ((current-level (funcall outline-level))
  22827. (max-level (org-get-valid-level
  22828. current-level (if level (prefix-numeric-value level) 1)))
  22829. (end (save-excursion (org-end-of-subtree t t)))
  22830. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22831. (past-first-child nil)
  22832. ;; Make sure to skip inlinetasks.
  22833. (re (format regexp-fmt
  22834. current-level
  22835. (cond
  22836. ((not (featurep 'org-inlinetask)) "")
  22837. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22838. 3))
  22839. (t (1- org-inlinetask-min-level))))))
  22840. ;; Display parent heading.
  22841. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22842. (forward-line)
  22843. ;; Display children. First child may be deeper than expected
  22844. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22845. ;; MAX-LEVEL accordingly.
  22846. (while (re-search-forward re end t)
  22847. (unless past-first-child
  22848. (setq re (format regexp-fmt
  22849. current-level
  22850. (max (funcall outline-level) max-level)))
  22851. (setq past-first-child t))
  22852. (outline-flag-region (line-end-position 0) (line-end-position) nil)))))
  22853. (defun org-show-subtree ()
  22854. "Show everything after this heading at deeper levels."
  22855. (interactive)
  22856. (outline-flag-region
  22857. (point)
  22858. (save-excursion
  22859. (org-end-of-subtree t t))
  22860. nil))
  22861. (defun org-show-entry ()
  22862. "Show the body directly following this heading.
  22863. Show the heading too, if it is currently invisible."
  22864. (interactive)
  22865. (save-excursion
  22866. (ignore-errors
  22867. (org-back-to-heading t)
  22868. (outline-flag-region
  22869. (max (point-min) (1- (point)))
  22870. (save-excursion
  22871. (if (re-search-forward
  22872. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22873. (match-beginning 1)
  22874. (point-max)))
  22875. nil)
  22876. (org-cycle-hide-drawers 'children))))
  22877. (defun org-make-options-regexp (kwds &optional extra)
  22878. "Make a regular expression for keyword lines.
  22879. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22880. when non-nil, is a regexp matching keywords names."
  22881. (concat "^[ \t]*#\\+\\("
  22882. (regexp-opt kwds)
  22883. (and extra (concat (and kwds "\\|") extra))
  22884. "\\):[ \t]*\\(.*\\)"))
  22885. ;; Make isearch reveal the necessary context
  22886. (defun org-isearch-end ()
  22887. "Reveal context after isearch exits."
  22888. (when isearch-success ; only if search was successful
  22889. (if (featurep 'xemacs)
  22890. ;; Under XEmacs, the hook is run in the correct place,
  22891. ;; we directly show the context.
  22892. (org-show-context 'isearch)
  22893. ;; In Emacs the hook runs *before* restoring the overlays.
  22894. ;; So we have to use a one-time post-command-hook to do this.
  22895. ;; (Emacs 22 has a special variable, see function `org-mode')
  22896. (unless (and (boundp 'isearch-mode-end-hook-quit)
  22897. isearch-mode-end-hook-quit)
  22898. ;; Only when the isearch was not quitted.
  22899. (org-add-hook 'post-command-hook 'org-isearch-post-command
  22900. 'append 'local)))))
  22901. (defun org-isearch-post-command ()
  22902. "Remove self from hook, and show context."
  22903. (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
  22904. (org-show-context 'isearch))
  22905. ;;;; Integration with and fixes for other packages
  22906. ;;; Imenu support
  22907. (defvar-local org-imenu-markers nil
  22908. "All markers currently used by Imenu.")
  22909. (defun org-imenu-new-marker (&optional pos)
  22910. "Return a new marker for use by Imenu, and remember the marker."
  22911. (let ((m (make-marker)))
  22912. (move-marker m (or pos (point)))
  22913. (push m org-imenu-markers)
  22914. m))
  22915. (defun org-imenu-get-tree ()
  22916. "Produce the index for Imenu."
  22917. (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
  22918. (setq org-imenu-markers nil)
  22919. (let* ((n org-imenu-depth)
  22920. (re (concat "^" (org-get-limited-outline-regexp)))
  22921. (subs (make-vector (1+ n) nil))
  22922. (last-level 0)
  22923. m level head0 head)
  22924. (save-excursion
  22925. (save-restriction
  22926. (widen)
  22927. (goto-char (point-max))
  22928. (while (re-search-backward re nil t)
  22929. (setq level (org-reduced-level (funcall outline-level)))
  22930. (when (and (<= level n)
  22931. (looking-at org-complex-heading-regexp)
  22932. (setq head0 (org-match-string-no-properties 4)))
  22933. (setq head (org-link-display-format head0)
  22934. m (org-imenu-new-marker))
  22935. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22936. (if (>= level last-level)
  22937. (push (cons head m) (aref subs level))
  22938. (push (cons head (aref subs (1+ level))) (aref subs level))
  22939. (loop for i from (1+ level) to n do (aset subs i nil)))
  22940. (setq last-level level)))))
  22941. (aref subs 1)))
  22942. (eval-after-load "imenu"
  22943. '(progn
  22944. (add-hook 'imenu-after-jump-hook
  22945. (lambda ()
  22946. (when (derived-mode-p 'org-mode)
  22947. (org-show-context 'org-goto))))))
  22948. (defun org-link-display-format (link)
  22949. "Replace a link with its the description.
  22950. If there is no description, use the link target."
  22951. (save-match-data
  22952. (if (string-match org-bracket-link-analytic-regexp link)
  22953. (replace-match (if (match-end 5)
  22954. (match-string 5 link)
  22955. (concat (match-string 1 link)
  22956. (match-string 3 link)))
  22957. nil t link)
  22958. link)))
  22959. (defun org-toggle-link-display ()
  22960. "Toggle the literal or descriptive display of links."
  22961. (interactive)
  22962. (if org-descriptive-links
  22963. (progn (org-remove-from-invisibility-spec '(org-link))
  22964. (org-restart-font-lock)
  22965. (setq org-descriptive-links nil))
  22966. (progn (add-to-invisibility-spec '(org-link))
  22967. (org-restart-font-lock)
  22968. (setq org-descriptive-links t))))
  22969. ;; Speedbar support
  22970. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22971. "Overlay marking the agenda restriction line in speedbar.")
  22972. (overlay-put org-speedbar-restriction-lock-overlay
  22973. 'face 'org-agenda-restriction-lock)
  22974. (overlay-put org-speedbar-restriction-lock-overlay
  22975. 'help-echo "Agendas are currently limited to this item.")
  22976. (org-detach-overlay org-speedbar-restriction-lock-overlay)
  22977. (defun org-speedbar-set-agenda-restriction ()
  22978. "Restrict future agenda commands to the location at point in speedbar.
  22979. To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
  22980. (interactive)
  22981. (require 'org-agenda)
  22982. (let (p m tp np dir txt)
  22983. (cond
  22984. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22985. 'org-imenu t))
  22986. (setq m (get-text-property p 'org-imenu-marker))
  22987. (with-current-buffer (marker-buffer m)
  22988. (goto-char m)
  22989. (org-agenda-set-restriction-lock 'subtree)))
  22990. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22991. 'speedbar-function 'speedbar-find-file))
  22992. (setq tp (previous-single-property-change
  22993. (1+ p) 'speedbar-function)
  22994. np (next-single-property-change
  22995. tp 'speedbar-function)
  22996. dir (speedbar-line-directory)
  22997. txt (buffer-substring-no-properties (or tp (point-min))
  22998. (or np (point-max))))
  22999. (with-current-buffer (find-file-noselect
  23000. (let ((default-directory dir))
  23001. (expand-file-name txt)))
  23002. (unless (derived-mode-p 'org-mode)
  23003. (user-error "Cannot restrict to non-Org-mode file"))
  23004. (org-agenda-set-restriction-lock 'file)))
  23005. (t (user-error "Don't know how to restrict Org-mode's agenda")))
  23006. (move-overlay org-speedbar-restriction-lock-overlay
  23007. (point-at-bol) (point-at-eol))
  23008. (setq current-prefix-arg nil)
  23009. (org-agenda-maybe-redo)))
  23010. (defvar speedbar-file-key-map)
  23011. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  23012. (eval-after-load "speedbar"
  23013. '(progn
  23014. (speedbar-add-supported-extension ".org")
  23015. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  23016. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  23017. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  23018. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  23019. (add-hook 'speedbar-visiting-tag-hook
  23020. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  23021. ;;; Fixes and Hacks for problems with other packages
  23022. (defun org--flyspell-object-check-p (element)
  23023. "Non-nil when Flyspell can check object at point.
  23024. ELEMENT is the element at point."
  23025. (let ((object (save-excursion
  23026. (when (org-looking-at-p "\\>") (backward-char))
  23027. (org-element-context element))))
  23028. (case (org-element-type object)
  23029. ;; Prevent checks in links due to keybinding conflict with
  23030. ;; Flyspell.
  23031. ((code entity export-snippet inline-babel-call
  23032. inline-src-block line-break latex-fragment link macro
  23033. statistics-cookie target timestamp verbatim)
  23034. nil)
  23035. (footnote-reference
  23036. ;; Only in inline footnotes, within the definition.
  23037. (and (eq (org-element-property :type object) 'inline)
  23038. (< (save-excursion
  23039. (goto-char (org-element-property :begin object))
  23040. (search-forward ":" nil t 2))
  23041. (point))))
  23042. (otherwise t))))
  23043. (defun org-mode-flyspell-verify ()
  23044. "Function used for `flyspell-generic-check-word-predicate'."
  23045. (if (org-at-heading-p)
  23046. ;; At a headline or an inlinetask, check title only. This is
  23047. ;; faster than relying on `org-element-at-point'.
  23048. (and (save-excursion (beginning-of-line)
  23049. (and (let ((case-fold-search t))
  23050. (not (looking-at "\\*+ END[ \t]*$")))
  23051. (looking-at org-complex-heading-regexp)))
  23052. (match-beginning 4)
  23053. (>= (point) (match-beginning 4))
  23054. (or (not (match-beginning 5))
  23055. (< (point) (match-beginning 5))))
  23056. (let* ((element (org-element-at-point))
  23057. (post-affiliated (org-element-property :post-affiliated element)))
  23058. (cond
  23059. ;; Ignore checks in all affiliated keywords but captions.
  23060. ((< (point) post-affiliated)
  23061. (and (save-excursion
  23062. (beginning-of-line)
  23063. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  23064. (> (point) (match-end 0))
  23065. (org--flyspell-object-check-p element)))
  23066. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  23067. ((let ((log (org-log-into-drawer)))
  23068. (and log
  23069. (let ((drawer (org-element-lineage element '(drawer))))
  23070. (and drawer
  23071. (eq (compare-strings
  23072. log nil nil
  23073. (org-element-property :drawer-name drawer) nil nil t)
  23074. t)))))
  23075. nil)
  23076. (t
  23077. (case (org-element-type element)
  23078. ((comment quote-section) t)
  23079. (comment-block
  23080. ;; Allow checks between block markers, not on them.
  23081. (and (> (line-beginning-position) post-affiliated)
  23082. (save-excursion
  23083. (end-of-line)
  23084. (skip-chars-forward " \r\t\n")
  23085. (< (point) (org-element-property :end element)))))
  23086. ;; Arbitrary list of keywords where checks are meaningful.
  23087. ;; Make sure point is on the value part of the element.
  23088. (keyword
  23089. (and (member (org-element-property :key element)
  23090. '("DESCRIPTION" "TITLE"))
  23091. (save-excursion
  23092. (search-backward ":" (line-beginning-position) t))))
  23093. ;; Check is globally allowed in paragraphs verse blocks and
  23094. ;; table rows (after affiliated keywords) but some objects
  23095. ;; must not be affected.
  23096. ((paragraph table-row verse-block)
  23097. (let ((cbeg (org-element-property :contents-begin element))
  23098. (cend (org-element-property :contents-end element)))
  23099. (and cbeg (>= (point) cbeg) (< (point) cend)
  23100. (org--flyspell-object-check-p element))))))))))
  23101. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  23102. (defun org-remove-flyspell-overlays-in (beg end)
  23103. "Remove flyspell overlays in region."
  23104. (and (org-bound-and-true-p flyspell-mode)
  23105. (fboundp 'flyspell-delete-region-overlays)
  23106. (flyspell-delete-region-overlays beg end)))
  23107. (defvar flyspell-delayed-commands)
  23108. (eval-after-load "flyspell"
  23109. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  23110. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  23111. (eval-after-load "bookmark"
  23112. '(if (boundp 'bookmark-after-jump-hook)
  23113. ;; We can use the hook
  23114. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  23115. ;; Hook not available, use advice
  23116. (defadvice bookmark-jump (after org-make-visible activate)
  23117. "Make the position visible."
  23118. (org-bookmark-jump-unhide))))
  23119. ;; Make sure saveplace shows the location if it was hidden
  23120. (eval-after-load "saveplace"
  23121. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  23122. "Make the position visible."
  23123. (org-bookmark-jump-unhide)))
  23124. ;; Make sure ecb shows the location if it was hidden
  23125. (eval-after-load "ecb"
  23126. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  23127. "Make hierarchy visible when jumping into location from ECB tree buffer."
  23128. (when (derived-mode-p 'org-mode)
  23129. (org-show-context))))
  23130. (defun org-bookmark-jump-unhide ()
  23131. "Unhide the current position, to show the bookmark location."
  23132. (and (derived-mode-p 'org-mode)
  23133. (or (outline-invisible-p)
  23134. (save-excursion (goto-char (max (point-min) (1- (point))))
  23135. (outline-invisible-p)))
  23136. (org-show-context 'bookmark-jump)))
  23137. (defun org-mark-jump-unhide ()
  23138. "Make the point visible with `org-show-context' after jumping to the mark."
  23139. (when (and (derived-mode-p 'org-mode)
  23140. (outline-invisible-p))
  23141. (org-show-context 'mark-goto)))
  23142. (eval-after-load "simple"
  23143. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23144. "Make the point visible with `org-show-context'."
  23145. (org-mark-jump-unhide)))
  23146. (eval-after-load "simple"
  23147. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23148. "Make the point visible with `org-show-context'."
  23149. (org-mark-jump-unhide)))
  23150. (eval-after-load "simple"
  23151. '(defadvice pop-global-mark (after org-make-visible activate)
  23152. "Make the point visible with `org-show-context'."
  23153. (org-mark-jump-unhide)))
  23154. ;; Make session.el ignore our circular variable
  23155. (defvar session-globals-exclude)
  23156. (eval-after-load "session"
  23157. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23158. ;;;; Finish up
  23159. (provide 'org)
  23160. (run-hooks 'org-load-hook)
  23161. ;;; org.el ends here