Matlab 파일의 헤더만 인쇄하도록 목록을 얻는 방법은 무엇입니까?

Matlab 파일의 헤더만 인쇄하도록 목록을 얻는 방법은 무엇입니까?

간단한 MATLAB 파일의 첫 번째 줄을 추출하는 방법그리고%그 바로 뒤의 다음 줄은 ? 문자로 시작합니다 . 추출할 줄 수를 알 수 없습니다. 그런 다음 listingsutf8추출된 코드를 표시하는 데 사용하고 싶습니다 .

MATLAB 파일의 예:

function myfunction(args)
% Comments
% about the function
% with an unknown number of lines
command1(); % another comment
command2();
% another comment
command3();
end

추출할 라인:

function myfunction(args)
% Comments
% about the function
% with an unknown number of lines

답변1

listings비교적 난해한 내부 매크로를 조합하여 이를 수행할 수 있습니다 . 외부 파일에 쓸 필요가 없습니다. 편의상 이라는 새로운 부울 키를 정의했습니다 onlyheader. 해당 키가 설정되면 주석 줄의 첫 번째 연속 블록(예: 함수 헤더) 이후의 모든 출력이 삭제됩니다.

편집하다: 이 기능은 다음에서 구현되었습니다.버전 0.2matlab-prettifier라는 키를 통해 mlonlyheader.

mlpr 출력

\documentclass{article}

\usepackage[T1]{fontenc}

% --- write to file ---
\usepackage{filecontents}
\begin{filecontents*}{code.txt}
function myfunction(args)
%MYFUNCTION One-line description goes here
% Comments
% about the function
% with an unknown number of lines
[ 2 3 4 ]
command1(); % another comment
command2();
% another comment
command3();
end
\end{filecontents*}

\usepackage[framed]{matlab-prettifier}

\lstset{style = Matlab-editor}

\begin{document}

\lstinputlisting
  [caption  = {\texttt{mlonlyheader=false}}]
  {code.txt}

\lstinputlisting
[
  caption    = {\texttt{mlonlyheader=true}},
  mlonlyheader = true,
]{code.txt}

\end{document}

만 사용listings

목록 출력

\documentclass{article}

% --- write to file ---
\usepackage{filecontents}
\begin{filecontents*}{code.txt}
function myfunction(args)
%MYFUNCTION One-line description goes here
% Comments
% about the function
% with an unknown number of lines
[ 2 3 4 ]
command1(); % another comment
command2();
% another comment
command3();
end
\end{filecontents*}

\usepackage{listings}

\makeatletter
% We define a new boolean key for convenience
\lst@Key{onlyheader}{false}[t]{\lstKV@SetIf{#1}\lst@ifonlyheader}

% We'll use this switch to keep track of where we are
\newif\iffirstnoncommentline

% --- Careful! the following modifications are global ---
% (i.e. will apply to all listings)
\lst@AddToHook{PreInit}{\global\firstnoncommentlinetrue}
\lst@AddToHook{Output}{\dropOutput}

\lst@AddToHook{OutputOther}{\dropOutput}

% helper macro
\newcommand\dropOutput
{%
  \lst@ifonlyheader%
    \ifnum\lst@lineno>1%  
      \lst@ifLmode%
      \else
        \iffirstnoncommentline%
          \lst@EnterMode\lst@Pmode{}%
          \lst@BeginDropOutput\lst@Pmode%
        \fi
        \global\firstnoncommentlinefalse%
      \fi
    \fi
  \fi
}
\makeatother

\lstset{
  language = Matlab,
  frame    = single,
}

\begin{document}

\lstinputlisting
  [caption  = {\texttt{onlyheader=false}}]
  {code.txt}

\lstinputlisting
[
  caption    = {\texttt{onlyheader=true}},
  onlyheader = true,
]{code.txt}

\lstinputlisting
[
  caption    = {\texttt{onlyheader=true}},
  onlyheader = true,
]{code.txt}

\end{document}

답변2

이러한 방식으로 파일을 처리하는 것은 반드시 TeX와 함께 올인원으로 가장 잘 처리되는 것은 아닙니다. TeX 외부에서 처리를 수행한 다음 TeX 내부에서 결과를 사용하는 것이 훨씬 더 좋습니다.

이 방법은 (에서 추출됨LaTeX의 변수에 쉘 출력을 어떻게 저장합니까?)은 다소 타협적인 것입니다. TeX 프리미티브를 사용하여 write18쉘 명령을 실행하고, 검색한 출력을 임시 파일에 저장합니다. 그러면 이 임시 파일이 목록 소스로 사용됩니다.

쉘 명령 해결 방법을 사용하지 않고 모든 TeX 기본 형식으로 이것이 수행될 수 있는지 여부와 방법을 여전히 연구 중입니다.

\documentclass{article}
\usepackage{listingsutf8}    
\begin{document}

% Execute a sed script to identify the lines that are desired
% from the top of your code file (note that the % sign has to be 
% escaped in this line, due to LaTeX interpreting it differently)
% This command was developed with sed on Mac OSX 10.9
\immediate\write18{sed -ne '1 h; 2,/^[^\%]/ {x;p;}' myfunction.txt > '\jobname.temp'}
                % Sed command:
                % 1 h; Take first line, hold in buffer
                % 2,/^[^%]/ Lines 2 through the next line that doesn't
                %     begin with a %
                % ... {x;p;}  Hold current line in buffer (swap with previous)
                %             and then print out previously held line
                % This results in line 1 + next continuous lines beginning with % printed

% Set language -- looked like MATLAB was a prime candidate given the syntax
\lstset{language=Matlab}

% Print out original function
Contents of \verb!myfunction.txt!:
\lstinputlisting{myfunction.txt}

% Print out newly created file
Dynamic header of \verb!myfunction.txt!:
\lstinputlisting{\jobname.temp}

% Clean up temporary file
\immediate\write18{rm -f -- '\jobname.temp'}

\end{document}

결과는

코드 예시 결과

답변3

패키지 filecontents는 입력할 파일을 생성하는 데에만 사용됩니다.

코드는 요청된 행을 가져옵니다. 직접 조작하거나 패키지 를 사용하여 조작할 수 있습니다 listings. 이를 위해 나는 다시 파일에 행을 작성하고 입력합니다. 확실히 더 쉽고 우아한 것이 있지만 listings. [업데이트는 추가됩니다 \lstset{language=Matlab}]

이 접근 방식에는 셸 이스케이프나 외부 도구가 필요하지 않습니다. 매크로는 \GetHeaderAndDisplayWithListing한 번에 작업을 수행합니다. 목록 자체는 다음을 통해 사용자 정의할 수 있는 것 같지만 \lstset매뉴얼의 3페이지에만 도달했습니다.

\documentclass{article}

\usepackage{listings}

\usepackage{filecontents}% only to create files for this example
\begin{filecontents*}{badboysamplefile.txt}
function myfunction(args)
% Comments
% about the function
% with an unknown number of lines
command1(); % another comment
command2();
% another comment
command3();
end
\end{filecontents*}

\begin{filecontents*}{badboyotherfile.txt}
function myfunction(args)
% 1 Comments
% 2 about the function
% 3 with an unknown number of lines
% 4 Comments
% 5 about the function
% 6 with an unknown number of lines
% 7 comments
% 1 Comments
% 2 about the function
% 3 with an unknown number of lines
% 4 Comments
% 5 about the function
% 6 with an unknown number of lines
% 7 comments
command1(); % another comment
command2();
% another comment
command3();
end
\end{filecontents*}

\makeatletter

\def\ExtractLines #1{%
 \newread\badboy 
 \openin\badboy #1\relax 
 \edef\ELrestore{\endlinechar\the\endlinechar\relax\catcode`\%=14 }%
 \endlinechar -1
 \ExtractLines@
 \ELrestore
 %\show\ELrestore
}%

\def\ExtractLines@ {%
    \ifeof\badboy 
       \def\ExtractedLines{}\closein\badboy
    \else
      \read\badboy to \ExtractedLines
      \edef\ExtractedLines{\detokenize\expandafter{\ExtractedLines}}%
      \catcode`\% 12
      \ExtractLines@@
    \fi
}

\def\ELSEP{\par}
\def\ELgetfirst #1#2\ELgetfirst {\def\ELFirst{#1}}

\catcode`\% 12
\catcode`! 14
\def\ExtractLines@@ {!
  \ifeof\badboy \closein\badboy\else
    \read\badboy to \Extract@OneLine
    \edef\Extract@@OneLine{\detokenize\expandafter{\Extract@OneLine}}!
    \expandafter\ELgetfirst\Extract@@OneLine.\ELgetfirst
    \if %\ELFirst 
      \expandafter\expandafter\expandafter
      \def\expandafter\expandafter\expandafter
      \ExtractedLines\expandafter\expandafter\expandafter
           {\expandafter\ExtractedLines\expandafter\ELSEP\Extract@@OneLine}!
      \expandafter\expandafter\expandafter
      \ExtractLines@@
    \else
       \closein\badboy
    \fi
  \fi
}
\catcode`% 14
\catcode`\! 12
\makeatother

\newcommand\GetHeaderAndDisplayWithListing [1]{%
   \def\ELSEP {^^J}%
   \ExtractLines {#1}%
   \newwrite\badboy
   \immediate\openout\badboy badboy-extracted.temp\relax
   \immediate\write\badboy {\ExtractedLines}%
   \immediate\closeout\badboy\relax
   \lstinputlisting {badboy-extracted.temp}%
   \def\ELSEP {\par}% just in case one wants to use \ExtractLines
   % and the produced \ExtractedLines directly
}

\begin{document}
% added in update:
\lstset{language=Matlab}

First file with \verb|listings|:\medskip

\GetHeaderAndDisplayWithListing {badboysamplefile.txt}

% \ExtractLines {badboysamplefile.txt}%
%  \texttt{\ExtractedLines}
% \bigskip

And the second file with \verb|listings|:\medskip

% \ExtractLines {badboyotherfile.txt}%
% \texttt{\ExtractedLines}

\GetHeaderAndDisplayWithListing {badboyotherfile.txt}

\end{document}

출력(현재 사용 중 \lstset{language=Matlab}):

목록이 포함된 추출된 라인 Matlab

listings이제 주석 처리된 \ExtractLines및 다음을 사용하여 초기 답변( package 가 필요하지 않음)의 출력 \texttt{\ExtractedLines}:

라인 추출

관련 정보