如何在 Latex 中缩进 Java 代码?

如何在 Latex 中缩进 Java 代码?

我有以下代码:

\documentclass{article}

\usepackage[brazilian]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\DeclareUnicodeCharacter{B0}{\textdegree}
% ---------------------------------------------------------------------------
% Pacotes Opcionais
% ---------------------------------------------------------------------------
\usepackage{rotating}           % Usado para rotacionar o texto
\usepackage[all,knot,arc,import,poly]{xy}   % Pacote para desenhos gráficos
% Este pacote pode conflitar com outros pacotes gráficos como o ``pictex''
% Então é necessário usar apenas um dos pacotes conflitantes
\newcommand{\VerbL}{0.52\textwidth}
\newcommand{\LatL}{0.42\textwidth}
\usepackage{abntex2cite}
\usepackage{tablefootnote}
\usepackage{lettrine}
\usepackage{multirow}
\usepackage{graphicx}
\usepackage{scalefnt}
\usepackage{hhline} 
\usepackage{caption}
\usepackage{pdflscape}
\usepackage{booktabs}
\usepackage{ltxtable} 
\usepackage{longtable}
\usepackage{enumitem}
\usepackage{xcolor}
\usepackage[nomargin,inline,marginclue,draft]{fixme}
\usepackage{enumitem} 
\makeatletter
\renewcommand*\FXLayoutInline[3]{%
  {\@fxuseface{inline}\ignorespaces[#3 \fxnotename{#1}: #2]}}
\makeatother

%\usepackage{caption}
\usepackage{subcaption}
%\usepackage{subfig}
\usepackage{float}

\renewcommand\thesubfigure{(\alph{subfigure})}
\makeatletter
\renewcommand{\p@subfigure}{\thefigure~} % unbreakable space after fig. num.
\makeatother

\definecolor{pblue}{rgb}{0.13,0.13,1}
\definecolor{pgreen}{rgb}{0,0.5,0}
\definecolor{pred}{rgb}{0.9,0,0}
\definecolor{pgrey}{rgb}{0.46,0.45,0.48}
\definecolor{gray}{rgb}{0.4,0.4,0.4}
\definecolor{darkblue}{rgb}{0.0,0.0,0.6}
\definecolor{cyan}{rgb}{0.0,0.6,0.6}

\usepackage{listings}

\lstset{language=Java,
  basicstyle=\ttfamily\footnotesize,
  showspaces=false,
  showtabs=false,
  breaklines=true,
  showstringspaces=false,
  breakatwhitespace=true,
  commentstyle=\color{pgreen},
  keywordstyle=\color{pblue},
  stringstyle=\color{pred},
  basicstyle=\ttfamily,
  moredelim=[il][\textcolor{pgrey}]{$$},
  moredelim=[is][\textcolor{pgrey}]{\%\%}{\%\%},
}


\usepackage[newfloat]{minted}
\usepackage{mdframed}
\usepackage{csquotes}
\renewcommand*{\mkcitation}[1]{ [#1]}

% %usar \nome{}
% \newcommand{\ricardo}[1]{\colorbox{ForestGreen}{\color{white}\textsf{\textbf{Ricardo}}} \textcolor{yellow}{#1}}
% \thispagestyle{empty}

\begin{document}

  \begin{lstlisting}[caption={Automated testing of Create, Read, Update and Delete (CRUD) of the Universities of the conventional approach},label=testesgrupoB, language=Java]

public class UniversitySystemTest{

    private PageUniversities pageUniversities;
    private LoadUniversity loadUniversity;

    @Before
    public void initialize() throws Exception {                                 
        pageUniversities = new PageUniversities();                  
        loadUniversity = new LoadUniversity();
        loadUniversity.performDataLoad();       
        pageUniversities.visitListUniversities();       
    }

    @Test
    public void addAUniversity() {  
        pageUniversities.new()
            .register(
                    "University Paulista", "Sao Paulo - SP", 
                    "Street Jardim Cris, n 40, Santo Amaro", "13572-000");      
        assertTrue(pageUniversities
            .existsInTheListing("University Paulista", "Sao Paulo - SP"));          
    }

    @Test
    public void deveRemoverUmaUniversity() {        
        pageUniversities._new().register("University Paulista","Sao Paulo - SP", "Rua Jardim Cris, n 40, Santo Amaro", "13572-000");
        assertTrue(pageUniversities.existsInTheListing("University Paulista", "Sao Paulo - SP"));
        pageUniversities.deleteUniversityInLastPosition();
        assertFalse(pageUniversities.existsInTheListing("University Paulista", "Sao Paulo - SP"));      
    }

    @Test
    public void mustListUniversities() {                
        int quantityOfUniversities = pageUniversities.getUniversityRecords().size();
        assertThat(quantityOfUniversities, is(10));
        assertThat(pageUniversities.getUniversityTableRodapeText(), is(quantityOfUniversities + " Universitys"));       
    }

    @Test
    public void mustEditAUniversity() {     
        pageUniversities._new().register("University Paulista", "Sao Paulo - SP", "Rua Jardim Cris, n 40, Santo Amaro", "13572-000");
        pageUniversities.changes().to("Federal University of Bahia", "Salvador - BA", "University Campus, n 127", " 40210-730");        
        assertFalse(pageUniversities.existsInTheListing("University Paulista", "Sao Paulo - SP"));
        assertTrue(pageUniversities.existsInTheListing("Federal University da Bahia", "Salvador - BA"));        
    }

    @After
    public void finalize(){
        loadUniversity.performDischarge();
    }
}

  \end{lstlisting}

\thispagestyle{empty}

\end{document}

但代码超出了范围。根据下图:

在此处输入图片描述 在此处输入图片描述

如何正确格式化 Java 代码,以便代码更好地缩进并位于页面边缘内?

答案1

我无法重现您的输出,因此这更像是一个评论而不是答案,但它可能有助于追踪问题。

首先精简你的 MWE,删除所有多余的包,只保留有问题的 Java 方法之一:

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{xcolor}

\definecolor{pblue}{rgb}{0.13,0.13,1}
\definecolor{pgreen}{rgb}{0,0.5,0}
\definecolor{pred}{rgb}{0.9,0,0}
\definecolor{pgrey}{rgb}{0.46,0.45,0.48}
\definecolor{gray}{rgb}{0.4,0.4,0.4}
\definecolor{darkblue}{rgb}{0.0,0.0,0.6}
\definecolor{cyan}{rgb}{0.0,0.6,0.6}

\usepackage{listings}

\lstset{language=Java,
  basicstyle=\ttfamily\footnotesize,
  showspaces=false,
  showtabs=false,
  breaklines=true,
  showstringspaces=false,
  breakatwhitespace=true,
  commentstyle=\color{pgreen},
  keywordstyle=\color{pblue},
  stringstyle=\color{pred},
  basicstyle=\ttfamily
}

\begin{document}

  \begin{lstlisting}[language=Java]

    @Test
    public void addAUniversity() {  
        pageUniversities.new()
            .register(
                    "University Paulista", "Sao Paulo - SP", 
                    "Street Jardim Cris, n 40, Santo Amaro", "13572-000");      
        assertTrue(pageUniversities
            .existsInTheListing("University Paulista", "Sao Paulo - SP"));          
    }

  \end{lstlisting}

\thispagestyle{empty}

\end{document}

这将使用空格字符而不是 TAB 并产生:

页面图像

这个网站似乎不支持 TAB,所以我把所有 8 个空格都替换成了 TAB 字符。下面^I代表一个 TAB 字符:

\begin{document}

  \begin{lstlisting}[language=Java]

    @Test
    public void addAUniversity() {  
^IpageUniversities.new()
^I    .register(
^I^I    "University Paulista", "Sao Paulo - SP", 
^I^I    "Street Jardim Cris, n 40, Santo Amaro", "13572-000");      
^IassertTrue(pageUniversities
^I    .existsInTheListing("University Paulista", "Sao Paulo - SP"));^I  
    }

  \end{lstlisting}

\thispagestyle{empty}

\end{document}

这仍然会产生与之前相同的输出,因此下一步是尝试加载geometryshowframe显示页面布局:

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[a4paper,showframe]{geometry}

\usepackage{xcolor}

\definecolor{pblue}{rgb}{0.13,0.13,1}
\definecolor{pgreen}{rgb}{0,0.5,0}
\definecolor{pred}{rgb}{0.9,0,0}
\definecolor{pgrey}{rgb}{0.46,0.45,0.48}
\definecolor{gray}{rgb}{0.4,0.4,0.4}
\definecolor{darkblue}{rgb}{0.0,0.0,0.6}
\definecolor{cyan}{rgb}{0.0,0.6,0.6}

\usepackage{listings}

\lstset{language=Java,
  basicstyle=\ttfamily\footnotesize,
  showspaces=false,
  showtabs=false,
  breaklines=true,
  showstringspaces=false,
  breakatwhitespace=true,
  commentstyle=\color{pgreen},
  keywordstyle=\color{pblue},
  stringstyle=\color{pred},
  basicstyle=\ttfamily
}

\begin{document}

  \begin{lstlisting}[language=Java]

    @Test
    public void addAUniversity() {  
        pageUniversities.new()
            .register(
                    "University Paulista", "Sao Paulo - SP", 
                    "Street Jardim Cris, n 40, Santo Amaro", "13572-000");      
        assertTrue(pageUniversities
            .existsInTheListing("University Paulista", "Sao Paulo - SP"));        
    }

  \end{lstlisting}

\thispagestyle{empty}

\end{document}

页面图像

如果您仍未获得此结果,请添加\listfiles,它显示所有软件包的版本号。可能是您使用了导致问题的其他版本。我得到了以下列表:

 *File List*
 article.cls    2014/09/29 v1.4h Standard LaTeX document class
  size10.clo    2014/09/29 v1.4h Standard LaTeX file (size option)
inputenc.sty    2015/03/17 v1.2c Input encoding file
    utf8.def    2017/01/28 v1.1t UTF-8 support for inputenc
   t1enc.dfu    2017/01/28 v1.1t UTF-8 support for inputenc
  ot1enc.dfu    2017/01/28 v1.1t UTF-8 support for inputenc
  omsenc.dfu    2017/01/28 v1.1t UTF-8 support for inputenc
 fontenc.sty
   t1enc.def    2017/04/05 v2.0i Standard LaTeX file
geometry.sty    2010/09/12 v5.6 Page Geometry
  keyval.sty    2014/10/28 v1.15 key=value parser (DPC)
   ifpdf.sty    2017/03/15 v3.2 Provides the ifpdf switch
  ifvtex.sty    2016/05/16 v1.6 Detect VTeX and its facilities (HO)
 ifxetex.sty    2010/09/12 v0.6 Provides ifxetex conditional
  xcolor.sty    2016/05/11 v2.12 LaTeX color extensions (UK)
   color.cfg    2016/01/02 v1.6 sample color configuration
  pdftex.def    2018/01/08 v1.0l Graphics/color driver for pdftex
listings.sty    2015/06/04 1.6 (Carsten Heinz)
 lstmisc.sty    2015/06/04 1.6 (Carsten Heinz)
listings.cfg    2015/06/04 1.6 listings configuration
lstlang1.sty    2015/06/04 1.6 listings language file
atbegshi.sty    2016/06/09 v1.18 At begin shipout hook (HO)
infwarerr.sty    2016/05/16 v1.4 Providing info/warning/error messages (HO)
 ltxcmds.sty    2016/05/16 v1.23 LaTeX kernel commands for general use (HO)
supp-pdf.mkii
  t1cmtt.fd    2014/09/29 v2.5h Standard LaTeX font definitions
 ***********

相关内容