4

CLion uses Apache's Velocity Template Language (VTL) to create templates for C++ and C files. On CLion's help (https://www.jetbrains.com/help/clion/file-template-variables.html) a bunch of variables that can be used are listed.

I was wondering however, if it would be possible to use the directory where a C++ file is created as a variable in one of my templates? I'm asking this because I like to structure my source files in a java/package-type fashion.

All files in the "Utils" directory are part of the "Utils" namespace, all packages in the "Ui" Directory are part of the "Ui" namespace etc...

So I was wondering if there's any way for me to obtain the parent directory of a file so I can use it in a template? (Maybe by setting a variable in my CMakeLists.txt?)

Here's an example of what I'd like to achieve

#parse("C File Header.h")
#[[#ifndef]]# ${INCLUDE_GUARD}
#[[#define]]# ${INCLUDE_GUARD}

${NAMESPACES_OPEN}
namespace ${CWD}

class ${NAME}
{

};

${NAMESPACES_CLOSE}

#[[#endif]]# //${INCLUDE_GUARD}

where ${CWD} represents the folder the file is in.

The ${NAMESPACE_OPEN} and ${NAMESPACE_CLOSE} directives seem to be purely symbolic for CLion, their websites lists it as "indicates the beginning/end of a namespace block created during refactoring."

shmoo6000
  • 495
  • 4
  • 22

1 Answers1

3

I'm happy to announce that this has been fixed in CLion 2019.1

By going to File -> Settings -> Editor -> Code Style -> C/C++ -> Naming Conventions the user can use some extra varibles ${PROJECT_REL_PATH}, ${FILE_NAME}, ${EXT}.

When using this, make sure to also check File -> Settings -> Editor -> File and Code Templates. The include guard you defined previously can be accessed here by using the ${INCLUDE_GUARD} variable.

Here's an example project and configuration to illustrate:

File -> Settings -> Editor -> File and Code Templates:

#parse("C File Header.h")
#[[#ifndef]]# ${INCLUDE_GUARD}
#[[#define]]# ${INCLUDE_GUARD}

${NAMESPACES_OPEN}

class ${NAME} {

};

${NAMESPACES_CLOSE}

#[[#endif]]# //${INCLUDE_GUARD}

File -> Settings -> Editor -> Code Style -> C/C++ -> Naming Conventions:

${PROJECT_REL_PATH}_${FILE_NAME}_${EXT}

Project Structure:

Project
├── CMakeLists.txt
├── cpp
│   ├── Test2.cpp
│   └── Test2.hpp
├── main.cpp
├── Test.cpp
└── Test.hpp

This gives a "Test.hpp" that looks like this:

//
// Created by user on 4/15/19.
//

#ifndef _TEST_HPP
#define _TEST_HPP


class test
{

};


#endif //_TEST_HPP

and a Test2.hpp of:

//
// Created by user on 4/15/19.
//

#ifndef CPP_TEST2_HPP
#define CPP_TEST2_HPP


class test2
{

};


#endif //CPP_TEST2_HPP
shmoo6000
  • 495
  • 4
  • 22