Search code examples
javaemacsyasnippet

How do I write a YASnippet that expands into a Java package declaration according to the buffer's directory?


Files that define Java classes can be organized into packages by declaring them to belong to particular package, e.g.

package foo.bar;

which declares that the file in question belongs to the subpackage bar of the package foo. The files are then stored in directories with a hierarchy corresponding to the hierarchy of the packages. Also, the root of the package hierarchy is usually some directory src. Is it possible to write a YASnippet that expands into a package declaration such it gets the package name from the path of the current file?


Solution

  • You can write a snippet with embedded Emacs Lisp that gets the buffer's path and converts it to a package name by treating the directory src as the root in the package hierarchy:

    # -*- mode: snippet -*-
    #name : package
    #key : pa
    # --
    package ${1:`(mapconcat 'identity (cdr (member "src" (split-string default-directory "/" t))) ".")`};$0
    

    This will recognize multi-level package hierarchies, i.e. if the path to the buffer of the file you are editing is /home/nn/src/foo/bar/Baz.java the snippet will expand to

    package foo.bar;
    

    Note that this requires you to use src as the root directory storing the package hierarchy. If there is directory named src in the path to the buffer the snippet will expand to

    package ;
    

    To have the snippet recognize some other directory as the root in the package hierarchy simply replace "src" with the desired directory name.