Skip to content

Commit

Permalink
Add doom-snippets for python-base-mode (#49)
Browse files Browse the repository at this point in the history
These snippets have been converted semi-automatically with the help of GPT-4 using the following prompt:

:PROPERTIES:
:GPTEL_MODEL: gpt-4
:GPTEL_BACKEND: ChatGPT
:GPTEL_SYSTEM: You are a large language model and a careful programmer. Provide code and only code as output without any additional text, prompt or note.
:GPTEL_BOUNDS: ((11612 . 15019))
:END:

* I want to convert emacs yasnipptes to tempo template format.

The templates are defined in a Lisp data file configured by ~tempel-path~. Lisp
data files are files containing Lisp s-expressions (see ~lisp-data-mode~). By
default the file =~/.config/emacs/templates= is used. The templates are grouped by
major mode with an optional ~:when~ condition. Each template is a list in the
concise form of the Emacs Tempo syntax. The first element of each list is the
name of the template. Behind the name, the Tempo syntax elements follow.

In addition, each template may specify a =:pre= and/or =:post= key with a FORM that is
evaluated before the template is expanded or after it is finalized, respectively. The
=:post= form is evaluated in the lexical scope of the template, which means that it can
access the template's named fields.

* Template syntax

All the Tempo syntax elements are fully supported. The syntax elements are
described in detail in the docstring of ~tempo-define-template~ in tempo.el:

Signature
(tempo-define-template NAME ELEMENTS &optional TAG DOCUMENTATION TAGLIST)

Documentation
Define a template.

This function creates a template variable tempo-template-NAME and an
interactive function tempo-template-NAME that inserts the template
at the point.  The created function is returned.

NAME is a string that contains the name of the template, ELEMENTS is a
list of elements in the template, TAG is the tag used for completion,
DOCUMENTATION is the documentation string for the insertion command
created, and TAGLIST (a symbol) is the tag list that TAG (if provided)
should be added to.  If TAGLIST is nil and TAG is non-nil, TAG is
added to tempo-tags.  If TAG already corresponds to a template in
the tag list, modify the list so that TAG now corresponds to the newly
defined template.

The elements in ELEMENTS can be of several types:

 - A string: It is sent to the hooks in tempo-insert-string-functions,
   and the result is inserted.
 - The symbol p: This position is saved in tempo-marks.
 - The symbol r: If tempo-insert is called with ON-REGION non-nil
   the current region is placed here.  Otherwise it works like p.
 - (p PROMPT <NAME> <NOINSERT>): If tempo-interactive is non-nil, the
   user is prompted in the minibuffer with PROMPT for a string to be
   inserted.  If the optional parameter NAME is non-nil, the text is
   saved for later insertion with the s tag.  If there already is
   something saved under NAME that value is used instead and no
   prompting is made.  If NOINSERT is provided and non-nil, nothing is
   inserted, but text is still saved when a NAME is provided.  For
   clarity, the symbol noinsert should be used as argument.
 - (P PROMPT <NAME> <NOINSERT>): Works just like the previous tag, but
   forces tempo-interactive to be true.
 - (r PROMPT <NAME> <NOINSERT>): Like the previous tag, but if
   tempo-interactive is nil and tempo-insert is called with
   ON-REGION non-nil, the current region is placed here.  This usually
   happens when you call the template function with a prefix argument.
 - (s NAME): Inserts text previously read with the (p ..) construct.
   Finds the insertion saved under NAME and inserts it.  Acts like p
   if tempo-interactive is nil.
 - &: If there is only whitespace between the line start and point,
   nothing happens.  Otherwise a newline is inserted.
 - %: If there is only whitespace between point and end of line,
   nothing happens.  Otherwise a newline is inserted.
 - n: Inserts a newline.
 - >: The line is indented using indent-according-to-mode.  Note
   that you often should place this item after the text you want on
   the line.
 - r>: Like r, but it also indents the region.
 - (r> PROMPT <NAME> <NOINSERT>): Like (r ...), but is also indents
   the region.
 - n>: Inserts a newline and indents line.
 - o: Like % but leaves the point before the newline.
 - nil: It is ignored.
 - Anything else: Each function in tempo-user-elements is called
   with it as argument until one of them returns non-nil, and the
   result is inserted.  If all of them return nil, it is evaluated and
   the result is treated as an element to be inserted.  One additional
   tag is useful for these cases.  If an expression returns a list (l
   foo bar), the elements after l will be inserted according to the
   usual rules.  This makes it possible to return several elements
   from one expression.

* Summary of Template Syntax

- "string" Inserts a string literal.
- ~p~ Inserts an unnamed placeholder field.
- ~n~ Inserts a newline.
- ~>~ Indents with ~indent-according-to-mode~.
- ~r~ Inserts the current region.
  If no region is active, quits the containing template when jumped to.
- ~r>~ Acts like ~r~, but indent region.
- ~n>~ Inserts a newline and indents.
- ~&~ Insert newline unless there is only whitespace between line start and point.
- ~%~ Insert newline unless there is only whitespace between point and line end.
- ~o~ Like ~%~ but leaves the point before newline.
- ~(s NAME)~ Inserts a named field.
- ~(p PROMPT <NAME> <NOINSERT>)~ Insert an optionally named field with a prompt.
  The ~PROMPT~ is displayed directly in the buffer as default value. If ~NOINSERT~
  is non-nil, no field is inserted. Then the minibuffer is used for prompting
  and the value is bound to ~NAME~.
- ~(r PROMPT <NAME> <NOINSERT>)~ Insert region or act like ~(p ...)~.
- ~(r> PROMPT <NAME> <NOINSERT>)~ Act like ~(r ...)~, but indent region.

Furthermore Tempel supports syntax extensions:

- ~(p FORM <NAME> <NOINSERT>)~ Like ~p~ described above, but ~FORM~ is evaluated.
- ~(FORM ...)~ Other Lisp forms are evaluated. Named fields are lexically bound.
- ~q~ Quits the containing template when jumped to.

Use caution with templates which execute arbitrary code!

* Tempel Template examples

  ;; ~/.config/emacs/templates

  fundamental-mode ;; Available everywhere

  (today (format-time-string "%Y-%m-%d"))

  prog-mode

  (fixme (if (derived-mode-p 'emacs-lisp-mode) ";; " comment-start) "FIXME ")
  (todo (if (derived-mode-p 'emacs-lisp-mode) ";; " comment-start) "TODO ")
  (bug (if (derived-mode-p 'emacs-lisp-mode) ";; " comment-start) "BUG ")
  (hack (if (derived-mode-p 'emacs-lisp-mode) ";; " comment-start) "HACK ")

  latex-mode

  (abstract "\\begin{abstract}\n" r> n> "\\end{abstract}")
  (align "\\begin{align}\n" r> n> "\\end{align}")
  (alignn "\\begin{align*}\n" r> n> "\\end{align*}")
  (gather "\\begin{gather}\n" r> n> "\\end{gather}")
  (gatherr "\\begin{gather*}\n" r> n> "\\end{gather*}")
  (appendix "\\begin{appendix}\n" r> n> "\\end{appendix}")
  (begin "\\begin{" (s env) "}" r> n> "\\end{" (s env) "}")
  (center "\\begin{center}\n" r> n> "\\end{center}")
  (displaymath "\\begin{displaymath}\n" r> n> "\\end{displaymath}")
  (document "\\begin{document}\n" r> n> "\\end{document}")
  (enumerate "\\begin{enumerate}\n\\item " r> n> "\\end{enumerate}")
  (equation "\\begin{equation}" r> n> "\\end{equation}")
  (flushleft "\\begin{flushleft}" r> n> "\\end{flushleft}")
  (flushright "\\begin{flushright}" r> n> "\\end{flushright}")
  (frac "\\frac{" p "}{" q "}")
  (fussypar "\\begin{fussypar}" r> n> "\\end{fussypar}")
  (itemize "\\begin{itemize}\n\\item " r> n> "\\end{itemize}")
  (letter "\\begin{letter}\n" r> n> "\\end{letter}")
  (math "\\begin{math}\n" r> n> "\\end{math}")
  (minipage "\\begin{minipage}[t]{0.5\linewidth}\n" r> n> "\\end{minipage}")
  (quotation "\\begin{quotation}\n" r> n> "\\end{quotation}")
  (quote "\\begin{quote}\n" r> n> "\\end{quote}")
  (sloppypar "\\begin{sloppypar}\n" r> n> "\\end{sloppypar}")
  (theindex "\\begin{theindex}\n" r> n> "\\end{theindex}")
  (trivlist "\\begin{trivlist}\n" r> n> "\\end{trivlist}")
  (verbatim "\\begin{verbatim}\n" r> n> "\\end{verbatim}")
  (verbatimm "\\begin{verbatim*}\n" r> n> "\\end{verbatim*}")

* These are the current doom snipptes for python-mode in the yasippet format.

def __contains__(self, el):
    $0# -*- mode: snippet -*-
def __enter__(self):
    $0

    return self# -*- mode: snippet -*-
def __exit__(self, type, value, traceback):
    $0# -*- mode: snippet -*-
def __len__(self):
    $0# -*- mode: snippet -*-
def __new__(mcs, name, bases, dict):
    $0
    return type.__new__(mcs, name, bases, dict)
__all__ = [
        $0
]# -*- mode: snippet -*-
parser.add_argument('-$1', '--$2',
                    $0)
parser.add_argument('${1:varname}', $0)# -*- mode: snippet -*-
assert $0# -*- mode: snippet -*-
self.assertEqual($1, $2)# -*- mode: snippet -*-
self.assertFalse($0)# -*- mode: snippet -*-
self.assertIn(${1:member}, ${2:container})# -*- mode: snippet -*-
self.assertNotEqual($1, $2)# -*- mode: snippet -*-
assertRaises(${1:Exception}, ${2:fun})# -*- mode: snippet -*-
with self.assertRaises(${1:Exception}):
     $0
self.assertTrue($0)# -*- mode: snippet -*-
from celery.contrib import rdb; rdb.set_trace()# -*- mode: snippet -*-
class ${1:Name}($2):
    $0# -*- mode: snippet -*-
@classmethod
def ${1:method_name}(cls, $1):
    $0# -*- mode: snippet -*-
def ${1:decorator}(func):
    $2
    def _$1(*args, **kwargs):
        $3
        ret = func(*args, **kwargs)
        $4
        return ret

    return _$1# -*- mode: snippet -*-
def ${1:func_name}($2):
    ${3:`(or % "pass")`}# -*- mode: snippet -*-
def ${1:method_name}(self${2:, $3}):
    ${4:`(or % "pass")`}# -*- mode: snippet -*-
"""$0
"""# -*- mode: snippet -*-
>>> ${1:function calls}
${2:desired output}
$0# -*- mode: snippet -*-
def __eq__(self, other):
    return self.$1 == other.$1# -*- mode: snippet -*-
for ${1:var} in ${2:collection}:
    ${3:`(or % "pass")`}# -*- mode: snippet -*-
from ${1:lib} import ${2:funs}# -*- mode: snippet -*-
def ${1:name}($2):
    \"\"\"$3
    ${2:$(python-args-to-docstring)}
    \"\"\"
    $0# -*- mode: snippet -*-
if ${1:cond}:
    ${2:`(or % "pass")`}# -*- mode: snippet -*-
if $1:
    ${2:`(or % "pass")`}
else:
    $0# -*- mode: snippet -*-
if __name__ == '__main__':
    ${1:`(or % "pass")`}# -*- mode: snippet -*-
import ${1:lib}${2: as ${3:alias}}
$0# -*- mode: snippet -*-
def __init__(self${1:, args}):
    $0# -*- mode: snippet -*-
def __init__(self$1):
    \"\"\"$2
    ${1:$(python-args-to-docstring)}
    \"\"\"
    $0# -*- mode: snippet -*-
import code; code.interact(local=locals())# -*- mode: snippet; require-final-newline: nil -*-
import ipdb; ipdb.set_trace()# -*- mode: snippet -*-
def __iter__(self):
    return ${1:iter($2)}# -*- mode: snippet -*-
lambda ${1:x}: $0# -*- mode: snippet -*-
[${1:x} for $1 in ${2:list}]# -*- mode: snippet -*-
logger = logging.getLogger(__name__)# -*- mode: snippet -*-
logger = logging.getLogger("${1:name}")
logger.setLevel(logging.${2:level})
def main():
    $0# -*- mode: snippet -*-
__metaclass__ = type# -*- mode: snippet -*-
def ${1:method_name}(self${2:, $3}):
    $0
def ${1:name}(self$2):
    \"\"\"$3
    ${2:$(python-args-to-docstring)}
    \"\"\"
    `%`$0# -*- mode: snippet -*-
raise NotImplementedError# -*- mode: snippet -*-
import numpy as np
$0# -*- mode: snippet -*-
def parse_arguments():
    parser = argparse.ArgumentParser(description='$1')
    $0
    return parser.parse_args()# -*- mode: snippet -*-
parser = argparse.ArgumentParser(description='$1')
$0# -*- mode: snippet -*-
pass# -*- mode: snippet -*-
print($0)# -*- mode: snippet -*-
def ${1:foo}():
   doc = """${2:Doc string}"""
   def fget(self):
       return self._$1

   def fset(self, value):
       self._$1 = value

   def fdel(self):
       del self._$1
   return locals()
$1 = property(**$1())

$0
${1:regexp} = re.compile(r"${2:expr}")
$0# -*- mode: snippet -*-
def __repr__(self):
    $0# -*- mode: snippet -*-
return $0# -*- mode: snippet -*-

def main():
   pass

if __name__ == '__main__':
   main()
self.$0# -*- mode: snippet -*-
self# -*- mode: snippet -*-
self.$1 = $1# -*- mode: snippet -*-
${1:var}.setdefault(${2:key}, []).append(${3:value})# -*- mode: snippet -*-
from setuptools import setup

package = '${1:name}'
version = '${2:0.1}'

setup(name=package,
      version=version,
      description="${3:description}",
      url='${4:url}'$0)
$0# -*- mode: snippet -*-
sys.getsizeof($0)# -*- mode: snippet -*-
@staticmethod
def ${1:method_name}($1):
    $0# -*- mode: snippet -*-
def __str__(self):
    $0# -*- mode: snippet -*-
super(${1:Class}, self).${2:function}(${3:args})# -*- mode: snippet -*-
class Test${1:toTest}(${2:unittest.TestCase}):
      $0
import unittest
${1:from ${2:test_file} import *}

$0

if __name__ == '__main__':
    unittest.main()# -*- mode: snippet -*-
import pdb; pdb.set_trace()# -*- mode: snippet -*-
try:
    ${1:`(or % "pass")`}
except ${2:Exception}:
    $0# -*- mode: snippet -*-
try:
    $1
except $2:
    $3
else:
    $0# -*- mode: snippet -*-
def __unicode__(self):
    $0# -*- mode: snippet -*-
while ${1:True}:
      $0# -*- mode: snippet -*-
with ${1:expr}${2: as ${3:alias}}:
     $0# -*- mode: snippet -*-
from __future__ import with_statement%

Please convert all the given yasnipptes to the new tempel format described above.
Avoid using "\n" for new lines, just use =n= symbol as described above.
Remember to use a lips symbol to define the template name, instead of a string.
So (templ_name ...) instead of ("templ_name").
  • Loading branch information
MArpogaus authored Feb 16, 2024
1 parent 65b92b4 commit 6248e22
Showing 1 changed file with 86 additions and 2 deletions.
88 changes: 86 additions & 2 deletions templates/python-base.eld
Original file line number Diff line number Diff line change
@@ -1,6 +1,90 @@
python-base-mode

(__contains__ "def __contains__(self, el):" n> p n> "pass")
(__enter__ "def __enter__(self):" n> p n> "return self")
(__eq__ "def __eq__(self, other):" n> "return self." p " == other." q)
(__exit__ "def __exit__(self, type, value, traceback):" n> p n> "pass")
(__getitem__ "def __len__(self):" n> p n> "pass")
(__iter__ "def __iter__(self):" n> "return " q)
(__new__ "def __new__(mcs, name, bases, dict):" n> p n> "return type.__new__(mcs, name, bases, dict)")
(__setitem__ "__all__ = [" n> p n> "]")
(arg "parser.add_argument('-" p "', '--" p "'," n> p ")")
(arg_positional "parser.add_argument('" p "', " p ")")
(assert "assert " q)
(assertEqual "self.assertEqual(" p ", " p ")")
(assertFalse "self.assertFalse(" p ")")
(assertIn "self.assertIn(" p ", " p ")")
(assertNotEqual "self.assertNotEqual(" p ", " p ")")
(assertRaises "assertRaises(" p ", " p ")")
(assertRaises-with "with self.assertRaises(" p "):" n> q)
(assertTrue "self.assertTrue(" p ")")
(celery_pdb "from celery.contrib import rdb; rdb.set_trace()")
(class "class " p "(" p "):" n> q)
(classmethod "@classmethod" n> "def " p "(cls, " p "):" n> q)
(def_decorator "def " p "(func):" n> p n> "def _" p "(*args, **kwargs):" n> p n> "ret = func(*args, **kwargs)" n> p n> "return ret" n n> "return _" q)
(def_function "def " p "(" p "):" n> q)
(doc "\"\"\"" p "\"\"\"")
(doctest ">>> " p n> q)
(for "for " p " in " p ":" n> q)
(tr & "import " p "; " p ".set_trace()" q)
(from "from " p " import " q)
(function_docstring "def " p "(" p "):" n> "\"\"\"" p "\"\"\"" n> q)
(if "if " p ":" n> q)
(ife "if " p ":" n> p n> "else:" n> q)
(ifmain "if __name__ == '__main__':" n> q)
(ig "# type: ignore" q)

(import "import " p q)
(init "def __init__(self" p "):" n> q)
(init_docstring "def __init__(self" p "):" n> "\"\"\"" p "\"\"\"" n> q)
(interact "import code; code.interact(local=locals())")
(ipdb_trace "import ipdb; ipdb.set_trace()")
(lambda "lambda " p ": " q)
(list "[" p " for " p " in " p "]")
(logger_name "logger = logging.getLogger(__name__)")
(logging "logger = logging.getLogger(\"" p "\")" n> "logger.setLevel(logging." p ")")
(main "def main():" n> q)
(metaclass "__metaclass__ = type")
(method "def " p "(self" p "):" n> q)
(method_docstring "def " p "(self" p "):" n> "\"\"\"" p "\"\"\"" n> q)
(not_impl "raise NotImplementedError")
(np "import numpy as np" n> q)
(parse_args "def parse_arguments():" n> "parser = argparse.ArgumentParser(description='" p "')" n> p n> "return parser.parse_args()")
(pd "import pandas as pd" n> q)
(tf "import tensorflow as tf" n> q)
(tr & "import " p "; " p ".set_trace()" q)
(parser "parser = argparse.ArgumentParser(description='" p "')" n> q)
(pass "pass")
(print "print(" p ")")
(prop "def " p "():"
n> "doc = \"\"\"" p "\"\"\""
n> "def fget(self):"
n> "return self._" p
n> n> "def fset(self, value):"
n> "self._" p " = value"
n> n> "def fdel(self):"
n> "del self._" p
n> "return locals()"
n> p " = property(**" p "())")
(reg p " = re.compile(r\"" p "\")")
(__repr__ "def __repr__(self):" n> q)
(return "return " q)
(script "#!/usr/bin/env python" n n> "def main():" n> "pass" n n> "if __name__ == '__main__':" n> "main()")
(self "self." q)
(self_without_dot "self")
(selfassign "self." p " = " q)
(setdef p ".setdefault(" p ", []).append(" p ")")
(setup "from setuptools import setup" n n> "package = '" p "'" n> "version = '" p "'" n n> "setup(name=package," n> "version=version," n> "description=\"" p "\"," n> "url='" p "'" p ")")
(shebang_line "#!/usr/bin/env python" n> q)
(size "sys.getsizeof(" p ")")
(static "@staticmethod" n> "def " p "(" p "):" n> q)
(__str__ "def __str__(self):" n> q)
(super "super(" p ", self)." p "(" p ")")
(test_class "class Test" p "(" p "):" n> q)
(test_file "import unittest" n> "from " p " import *" n> p n> "if __name__ == '__main__':" n> "unittest.main()")
(trace "import pdb; pdb.set_trace()")
(try "try:" n> p n> "except " p ":" n> q)
(tryelse "try:" n> p n> "except " p ":" n> p n> "else:" n> q)
(__unicode__ "def __unicode__(self):" n> q)
(utf-8_encoding "# -*- coding: utf-8 -*-")
(while "while " p ":" n> q)
(with "with " p p ":" n> q)
(with_statement "from __future__ import with_statement"))

0 comments on commit 6248e22

Please sign in to comment.