Regular expression with listings to extract filename from path
expl3
got you covered. There is a function built in \file_parse_full_name:nNNN
, which we can use here. I created a macro from it which you can use to typeset different parts of the file name. If the optional argument includes a d
the directory will be printed, if it contains an f
the file name will be printed, if it contains an e
the extension will be printed, order doesn't matter. By default it uses fe
so prints the file name and the extension, but not the directory (as you wanted it to be).
\documentclass[11pt]{article}
\usepackage{listings}
\usepackage{xparse}
\ExplSyntaxOn
\tl_new:N \l_Skjerning_dir_tl
\tl_new:N \l_Skjerning_file_tl
\tl_new:N \l_Skjerning_ext_tl
\NewDocumentCommand \GetFileName { O{fe} m }
{
\file_parse_full_name:eNNN { #2 }
\l_Skjerning_dir_tl
\l_Skjerning_file_tl
\l_Skjerning_ext_tl
\tl_if_in:nnT { #1 } { d } { \l_Skjerning_dir_tl / }
\tl_if_in:nnT { #1 } { f } \l_Skjerning_file_tl
\tl_if_in:nnT { #1 } { e } \l_Skjerning_ext_tl
}
\cs_generate_variant:Nn \file_parse_full_name:nNNN { eNNN }
\ExplSyntaxOff
\lstset {
title = {\GetFileName{\lstname}}
}
\begin{document}
\lstinputlisting{./../src/main.py}
\end{document}
You can specify the path with the inputpath
option to \lstset
and provide the file name with an intermediary macro:
\documentclass[11pt]{article}
\usepackage{listings}
\lstset {
inputpath=./../src,
title = \myname
}
\begin{document}
\def\myname{main.py}
\lstinputlisting{\myname}
\def\myname{test.py}
\lstinputlisting{\myname}
\end{document}
EDIT: a more generic and easier to handle approach would be to strip away the path part as long as your source files are always located in a folder named src
:
\documentclass[11pt]{article}
\usepackage{listings}
\def\extractPath#1src/#2\relax{#2}
\lstset{title = \expandafter\extractPath\lstname\relax}
\begin{document}
\lstinputlisting{./../src/main.py}
\lstinputlisting{./../src/test.py}
\end{document}