1

Hi i am trying to add an inline code block in a Latex document. I know how to add a separate code block using lstlisting but i want to instead add an inline code block. I am attaching the screenshot of output that i am expecting .As you can see in the same line a code block is added which contains the expression print(g). I want something like that. So that it should be customizable that is the background color of the box, width and height of the box, border width etc. Also the text of the code inside that inline code block should be customizable as well. Is there a way to achieve this in Latex? Below is the screenshot.

enter image description here

0

2 Answers 2

2

It is possible, and here is one way do it. (This code is an excerpt from a package I maintain and for some reason, realboxes must be loaded after xcolor whereas in my package, which loads several other packages, that is not the case and I'm not yet sure why.)

The background color is an argument to the \Colorbox command.

% !TEX program = lualatexmk
% !TEX encoding = UTF-8 Unicode

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{realboxes} % needed for \Colorbox

\definecolor{gsbggray}     {rgb}{0.90,0.90,0.90} % background gray
\definecolor{gsgray}       {rgb}{0.30,0.30,0.30} % gray
\definecolor{gsgreen}      {rgb}{0.00,0.60,0.00} % green
\definecolor{gsorange}     {rgb}{0.80,0.45,0.12} % orange
\definecolor{gspeach}      {rgb}{1.00,0.90,0.71} % peach
\definecolor{gspearl}      {rgb}{0.94,0.92,0.84} % pearl
\definecolor{gsplum}       {rgb}{0.74,0.46,0.70} % plum
\lstdefinestyle{vpython}{%                       % style for listings
  backgroundcolor=\color{gsbggray},%             % background color
  basicstyle=\footnotesize,%                     % default style
  breakatwhitespace=true%                        % break at whitespace
  breaklines=true,%                              % break long lines
  captionpos=b,%                                 % position caption
  classoffset=1,%                                % STILL DON'T UNDERSTAND THIS
  commentstyle=\color{gsgray},%                  % font for comments
  deletekeywords={print},%                       % delete keywords from the given language
  emph={self,cls,@classmethod,@property},%       % words to emphasize
  emphstyle=\color{gsorange}\itshape,%           % font for emphasis
  escapeinside={(*@}{@*)},%                      % add LaTeX within your code
  frame=tb,%                                     % frame style
  framerule=2.0pt,%                              % frame thickness
  framexleftmargin=5pt,%                         % extra frame left margin
  %identifierstyle=\sffamily,%                    % style for identifiers
  keywordstyle=\sffamily\color{gsplum},%         % color for keywords
  language=Python,%                              % select language
  linewidth=\linewidth,%                         % width of listings
  morekeywords={%                                % VPython/GlowScript specific keywords
    __future__,abs,acos,align,ambient,angle,append,append_to_caption,%
    append_to_title,arange,arrow,asin,astuple,atan,atan2,attach_arrow,%
    attach_trail,autoscale,axis,background,billboard,bind,black,blue,border,%
    bounding_box,box,bumpaxis,bumpmap,bumpmaps,camera,canvas,caption,capture,%
    ceil,center,clear,clear_trail,click,clone,CoffeeScript,coils,color,combin,%
    comp,compound,cone,convex,cos,cross,curve,cyan,cylinder,data,degrees,del,%
    delete,depth,descender,diff_angle,digits,division,dot,draw_complete,%
    ellipsoid,emissive,end_face_color,equals,explog,extrusion,faces,factorial,%
    False,floor,follow,font,format,forward,fov,frame,gcurve,gdisplay,gdots,%
    get_library,get_selected,ghbars,global,GlowScript,graph,graphs,green,gvbars,%
    hat,headlength,headwidth,height,helix,hsv_to_rgb,index,interval,keydown,%
    keyup,label,length,lights,line,linecolor,linewidth,logx,logy,lower_left,%
    lower_right,mag,mag2,magenta,make_trail,marker_color,markers,material,%
    max,min,mouse,mousedown,mousemove,mouseup,newball,norm,normal,objects,%
    offset,one,opacity,orange,origin,path,pause,pi,pixel_to_world,pixels,plot,%
    points,pos,pow,pps,print,print_function,print_options,proj,purple,pyramid,%
    quad,radians,radius,random,rate,ray,read_local_file,readonly,red,redraw,%
    retain,rgb_to_hsv,ring,rotate,round,scene,scroll,shaftwidth,shape,shapes,%
    shininess,show_end_face,show_start_face,sign,sin,size,size_units,sleep,%
    smooth,space,sphere,sqrt,start,start_face_color,stop,tan,text,textpos,%
    texture,textures,thickness,title,trail_color,trail_object,trail_radius,%
    trail_type,triangle,trigger,True,twist,unbind,up,upper_left,upper_right,%
    userpan,userspin,userzoom,vec,vector,vertex,vertical_spacing,visible,%
    visual,vpython,VPython,waitfor,white,width,world,xtitle,yellow,yoffset,%
    ytitle%
  },%
  morekeywords={print,None,TypeError},%          % additional keywords
  morestring=[b]{"""},%                          % treat triple quotes as strings
  numbers=left,%                                 % where to put line numbers
  numbersep=10pt,%                               % how far line numbers are from code
  numberstyle=\bfseries\tiny,%                   % set to 'none' for no line numbers
  showstringspaces=false,%                       % show spaces in strings
  showtabs=false,%                               % show tabs within strings
  stringstyle=\color{gsgreen},%                  % color for strings
  upquote=true,%                                 % how to typeset quotes
}%

\newcommand*{\pythonline}[1]{\Colorbox{gsbggray}{\lstinline[style=vpython]{#1}}}

\begin{document}

You can type \pythonline{print("Hello, world!")} as your first program.

\end{document}

MWE Output

UPDATE:

Here is a variant showing how to use tcolorbox to achieve your, hopefully, desired results. Play with the options!

% !TEX program = lualatexmk
% !TEX encoding = UTF-8 Unicode

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{realboxes} % needed for \Colorbox
\usepackage[most]{tcolorbox}

\definecolor{gsbggray}     {rgb}{0.90,0.90,0.90} % background gray
\definecolor{gsgray}       {rgb}{0.30,0.30,0.30} % gray
\definecolor{gsgreen}      {rgb}{0.00,0.60,0.00} % green
\definecolor{gsorange}     {rgb}{0.80,0.45,0.12} % orange
\definecolor{gspeach}      {rgb}{1.00,0.90,0.71} % peach
\definecolor{gspearl}      {rgb}{0.94,0.92,0.84} % pearl
\definecolor{gsplum}       {rgb}{0.74,0.46,0.70} % plum
\lstdefinestyle{vpython}{%                       % style for listings
  backgroundcolor=\color{gsbggray},%             % background color
  basicstyle=\footnotesize,%                     % default style
  breakatwhitespace=true%                        % break at whitespace
  breaklines=true,%                              % break long lines
  captionpos=b,%                                 % position caption
  classoffset=1,%                                % STILL DON'T UNDERSTAND THIS
  commentstyle=\color{gsgray},%                  % font for comments
  deletekeywords={print},%                       % delete keywords from the given language
  emph={self,cls,@classmethod,@property},%       % words to emphasize
  emphstyle=\color{gsorange}\itshape,%           % font for emphasis
  escapeinside={(*@}{@*)},%                      % add LaTeX within your code
  frame=tlrb,%                                     % frame style
  framerule=2.0pt,%                              % frame thickness
  framexleftmargin=5pt,%                         % extra frame left margin
  %identifierstyle=\sffamily,%                    % style for identifiers
  keywordstyle=\sffamily\color{gsplum},%         % color for keywords
  language=Python,%                              % select language
  linewidth=\linewidth,%                         % width of listings
  morekeywords={%                                % VPython/GlowScript specific keywords
    __future__,abs,acos,align,ambient,angle,append,append_to_caption,%
    append_to_title,arange,arrow,asin,astuple,atan,atan2,attach_arrow,%
    attach_trail,autoscale,axis,background,billboard,bind,black,blue,border,%
    bounding_box,box,bumpaxis,bumpmap,bumpmaps,camera,canvas,caption,capture,%
    ceil,center,clear,clear_trail,click,clone,CoffeeScript,coils,color,combin,%
    comp,compound,cone,convex,cos,cross,curve,cyan,cylinder,data,degrees,del,%
    delete,depth,descender,diff_angle,digits,division,dot,draw_complete,%
    ellipsoid,emissive,end_face_color,equals,explog,extrusion,faces,factorial,%
    False,floor,follow,font,format,forward,fov,frame,gcurve,gdisplay,gdots,%
    get_library,get_selected,ghbars,global,GlowScript,graph,graphs,green,gvbars,%
    hat,headlength,headwidth,height,helix,hsv_to_rgb,index,interval,keydown,%
    keyup,label,length,lights,line,linecolor,linewidth,logx,logy,lower_left,%
    lower_right,mag,mag2,magenta,make_trail,marker_color,markers,material,%
    max,min,mouse,mousedown,mousemove,mouseup,newball,norm,normal,objects,%
    offset,one,opacity,orange,origin,path,pause,pi,pixel_to_world,pixels,plot,%
    points,pos,pow,pps,print,print_function,print_options,proj,purple,pyramid,%
    quad,radians,radius,random,rate,ray,read_local_file,readonly,red,redraw,%
    retain,rgb_to_hsv,ring,rotate,round,scene,scroll,shaftwidth,shape,shapes,%
    shininess,show_end_face,show_start_face,sign,sin,size,size_units,sleep,%
    smooth,space,sphere,sqrt,start,start_face_color,stop,tan,text,textpos,%
    texture,textures,thickness,title,trail_color,trail_object,trail_radius,%
    trail_type,triangle,trigger,True,twist,unbind,up,upper_left,upper_right,%
    userpan,userspin,userzoom,vec,vector,vertex,vertical_spacing,visible,%
    visual,vpython,VPython,waitfor,white,width,world,xtitle,yellow,yoffset,%
    ytitle%
  },%
  morekeywords={print,None,TypeError},%          % additional keywords
  morestring=[b]{"""},%                          % treat triple quotes as strings
  numbers=left,%                                 % where to put line numbers
  numbersep=10pt,%                               % how far line numbers are from code
  numberstyle=\bfseries\tiny,%                   % set to 'none' for no line numbers
  showstringspaces=false,%                       % show spaces in strings
  showtabs=false,%                               % show tabs within strings
  stringstyle=\color{gsgreen},%                  % color for strings
  upquote=true,%                                 % how to typeset quotes
}%

\newcommand*{\pythonline}[1]{\Colorbox{gsbggray}{\lstinline[style=vpython]{#1}}}
\DeclareTotalTCBox{\tcbpythonline}{ m }{%
  leftrule=0.1mm,%
  rightrule=0.1mm,%
  toprule=0.1mm,%
  bottomrule=0.1mm,%
  sharp corners,%
  top=0pt,%
  bottom=0pt,%
  left=0pt,%
  right=0pt,%
  tcbox raise base,%
  boxsep=1.0mm,%
  nobeforeafter,%
  }{\lstinline[style=vpython]{#1}}

\begin{document}

You can type \pythonline{print("Hello, world!")} as your first program.

You can type \tcbpythonline{print("Hello, world!")} as your first program.

\end{document}

New MWE Output

2
  • Can we add border width and color using this? This looks good . Thanks man.
    – Jason
    Feb 15, 2021 at 8:49
  • 1
    Not with listings unfortunately, but I've added a variant showing how to use the immensely powerful tcolorbox package. Feb 15, 2021 at 14:01
2

Since you're familiar with the listings package and its lstlisting environment, you could use its \lstinline macro to typeset, well, an inline code block.

enter image description here

\documentclass{article}
\usepackage{listings} % for '\lstset' and '\lstinline' macros
% For this example, we use just a very basic set of arguments for \lstset:
\lstset{basicstyle=\ttfamily,keywordstyle=\underbar,morekeywords={print}}
\begin{document}
\sffamily\bfseries % just to mimic the OP's screenshot
The command \lstinline{print(g)} prints something.
\end{document}
3
  • Is it possible to add the kind of customization that i expect, using this macro? The background color and the border width and color? Thanks
    – Jason
    Feb 14, 2021 at 9:12
  • 1
    @JasonLiam - In my opinion, the listings package wisely doesn't provide too many options for decorating inline code, as otherwise pages quickly start to look like overly decorated, gaudy Christmas trees. Much too distracting, really. In particular, AFAICT, background color and framelines around inline code blocks are not supported. If you simply can't do without those questionable visual distractions, all I can suggest is that you look into the capabilities of the fancyvrb package.
    – Mico
    Feb 14, 2021 at 9:20
  • I found another link to \colorbox macro. It seems to do the trick but still i don't think border width is possible using colorbox. I ll read more about it and your link as well.
    – Jason
    Feb 14, 2021 at 9:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .