Skip to content

Instantly share code, notes, and snippets.

@tbnorth
Last active December 17, 2015 01:39
Show Gist options
  • Save tbnorth/5530059 to your computer and use it in GitHub Desktop.
Save tbnorth/5530059 to your computer and use it in GitHub Desktop.
My leo-editor @settings / @DaTa abbreviations (first) and @settings / @DaTa abbreviations-subst-env (second)
# Comments lines (lines starting with '#') are ignored.
# Non-comment lines should have the form::
#
# name=definition
# Definitions in @data abbreviation nodes override definitions in @data
# global-abbreviation nodes. Typically you would define @data abbreviation nodes
# in myLeoSettings.leo
# jump to and select next placeholder
,,={|{x='__NEXT_PLACEHOLDER'}|}
# date insertions
date;;={|{x=time.asctime()}|}
ts;;={|{x=time.strftime("%Y%m%d%H%M%S")}|}
tss;;={|{x=time.strftime("%Y%m%d")}|}
# dynamic abbreviation alternative, not as smart as core
;;;={|{x=long_word()}|}
# close xml element
<;;={|{x=close_xml()}|}
# python main template
""";;=@language python
\:"""
\:<||>{|{x=file_name()}|} - <|describe|>
\:
\:{|{x=user_name()}|}, Terry_N_Brown@yahoo.com, {|{x=time.asctime()}|}
\:"""
\:
\:import os
\:import sys
\:
\:def main():
\: <|code|>
\:
\:if __name__ == '__main__':
\: main()\n
# python class template
class;;=class {|{
\:x=ask("Class name",default=c.p.h.replace('class ',''))}|}(object):
\: """{|{x=get("Class name")}|} - <|describe class|>
\: """
\:
\: def __init__(self{|{
\:x = ask("__init__ params, comma sep.");
\:if x: x = ", " + x}|}):
\: """<|describe init|>{|{x=param_doc("__init__ params, comma sep.")}|}
\: """
\: <|code|>
\:
\: @others
# python method template
def;;=def {|{x=ask("function name",default=c.p.h)}|}({|{x=in_class()}|}{|{x=ask("Params, comma sep.")}|}):
\: """{|{x=get("function name")}|} - Return <||>{|{x=param_doc()}|}
\: """
\:
\: <|code|>
# python argparser template
iap;;=import argparse
\:
\:def make_parser():
\:
\: parser = argparse.ArgumentParser(
\: description="""<|general description|>""",
\: formatter_class=argparse.ArgumentDefaultsHelpFormatter
\: )
\:
\: parser.add_argument("--<|foo|>", action='store_true',
\: help="<|help|>"
\: )
\: parser.add_argument('<|positional(s)|>', type=str, nargs='+',
\: help="<|help|>"
\: )
\:
\: return parser
\:
\: opt = make_parser().parse_args()
# python persistence with json
persist;;=import json
\:
\:json_state_file = "<|persistent_info|>.json"
\:if not os.path.exists(json_state_file):
\: json.dump({'<|top_level|>':{}}, open(json_state_file, 'w'))
\:{|{x=get("persistent variable name", "state")}|} = json.load(open(json_state_file))
\:
\:def main():
\:
\: <|code|>
\:
\:if __name__ == '__main__':
\:
\: try:
\: main()
\: finally:
\: json.dump({|{x=get("persistent variable name")}|}, open(json_state_file, 'w'))
# rst image
image;;=.. image:: <|filename|>.png
\: :width: 80%
# rst csv table
csv-table;;=.. csv-table::
\: :header: "<|col 1|>", "", "", ""
\: :widths: 1, 1, 1, 1
\:
\: <|data|>
# close django tag
};;={|{django_tag();x=''}|}
# bash case statement
case;;=case <|var|> in
\:<|case|>)
\: <|code|>
\:;;
\:<|case|>)
\: <|code|>
\:;;
\:*)
\: <|default code|>
\:;;
\:esac
# SQL copy query result into variable
\set;;=select <|fields|> into temp {|{x=ask("variable")}|} from <|source|> where <|condition|>;
\:\set {|{x=get("variable")}|} '(select * from {|{x=get("variable")}|})'
# SQL indented query
select;;=select *<|fields|>
\: from join using()
\: where
\: group by
\: order by
\:;
# start new R knitr block
..r=.. {r <|{|{x=rname()}|}|>}
\: <|code|>
\:.. ..
# insert text in middle of R knitr block
..i=.. ..
\:
\:<|This is necessary because |>
\:
\:.. {r {|{x=rname()}|}}
# R .Rrst knitr template
..R=
\:.. role:: m(raw)
\: :format: html latex
\:.. role:: latex(raw)
\: :format: latex
\:
\:.. to get R environment
\:
\: library(knitr)
\: purl('FOO.Rrst')
\: source('FOO.R')
\:
\:.. {r init. setup, echo=F, message=F}
\:library('knitr')
\:opts_chunk$set(comment=NA, fig.cap='', dev='pdf', tidy=F)
\:.. ..
import os
import sys
import time
import datetime
import re
try:
\: import pwd
\:except:
\: pwd = None
def ask(s, default=""):
\: x = g.app.gui.runAskOkCancelStringDialog(c, s, s, default=default)
\: _values[s] = x
\: return x
def get(s, default=""):
\: if s in _values:
\: return _values[s]
\: else:
\: return ask(s, default=default)
def user_name():
\: if pwd:
\: return pwd.getpwnam(os.environ['LOGNAME']).pw_gecos.rstrip(',')
\: else:
\: os.environ['LOGNAME']
def file_name():
\: if c.p.h.endswith(".py"):
\: return g.os_path_split(c.p.h)[-1]
\: return ".py"
def in_class(): # return "self, " if in a class definition
\: for nd in c.p.self_and_parents_iter():
\: if nd.h.startswith('class'):
\: return "self, "
\: return ""
def param_doc(k=None):
\: if not k:
\: k = "Params, comma sep."
\: indent = ' '
\: else: # assume in an __init__ def'n
\: indent = ' '
\: if k in _values and _values[k]:
\: return "\n\n%s:Parameters:\n%s" % (indent, '\n'.join(
\: ["%s- `%s`: <|describe %s|>" % (
\: indent, i.split('=',1)[0].strip(), i.split('=',1)[0].strip()
\: ) for i in _values[k].split(',')]))
\: return ""
def long_word():
\: words = c.p.b.split()
\: w = c.frame.body.bodyCtrl
\: i = w.getInsertPoint() - len(_abr)
\: b = c.p.b
\: s = []
\: while i and b[i].isalpha():
\: s[0:0] = b[i]
\: i -= 1
\: s = ''.join(s)
\: for i in words:
\: if i.startswith(s) and i != s:
\: return i[len(s):]
\:
\: return ''
def close_xml():
\: w = c.frame.body.bodyCtrl
\: i = w.getInsertPoint() - len(_abr)
\: b = c.p.b
\: skips = 1
\: while i and skips:
\: s = []
\: while i and b[i] != '>':
\: i -= 1
\: i -= 1
\: while i and (b[i] != '<' or (s and b[i] == '<' and s[0] == '/')):
\: s[0:0] = b[i]
\: i -= 1
\: if s and s[0] == '<' and len(s) > 1 and s[1] == '/':
\: skips += 1
\: skips -= 1
\: s = ''.join([i if i.isalpha() else ' ' for i in s])
\: if s.strip():
\: return "</%s>" % (s.split(None, 1)[0])
\: else:
\: return "</"
def django_tag():
\: from PyQt4 import QtCore
\: w = c.frame.body.bodyCtrl
\: i = w.getInsertPoint() - len(_abr)
\: b = c.p.b
\: s = []
\: while i and b[i] != '{':
\: s[0:0] = b[i]
\: i -= 1
\: start = i
\: s = ''.join(s)
\: indent = 0
\: while i and b[i] != '\n':
\: indent += 1
\: i -= 1
\: if indent:
\: indent -= 1
\: def later(c=c, indent=indent, b=b, s=s, _abr=_abr):
\: c.p.b = "%s{%% %s %%}\n %s\n%s{%% end%s %%}%s" % (
\: b[:start], s, ' '*indent, ' '*indent, s, b[start+len(s)+len(_abr):]
\: )
\: QtCore.QTimer.singleShot(0, later)
def rname(): # R package `knitr` - insert new chunk with new name and previous args
\: n = 0
\: while 'block%02d'%n in c.p.b:
\: n += 1
\: w = c.frame.body.bodyCtrl
\: i = w.getInsertPoint() - len(_abr)
\: pos = 0
\: last = ""
\: for line in c.p.b.split('\n'):
\: if ".. {r" in line:
\: last = line
\: pos += len(line)+1
\: if pos >= i:
\: break
\: args = ' '.join(last.split()[3:]).strip('}') if last else ''
\: return 'block%02d %s'%(n,args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment