It is easy to define your own output hooks in knitr to decorate your results with the LaTeX listings package. Here is a snippet that you may use:
## a common hook for messages, warnings and errors
hook_lst_bf = function(x, options) {
paste("\\begin{lstlisting}[basicstyle={\\bfseries}]\n", x,
"\\end{lstlisting}\n", sep = "")
}
knit_hooks$set(source = function(x, options) {
paste("\\begin{lstlisting}[language=R,numbers=left,stepnumber=2]\n", x,
"\\end{lstlisting}\n", sep = "")
}, output = function(x, options) {
paste("\\begin{lstlisting}[basicstyle={\\ttfamily}]\n", x,
"\\end{lstlisting}\n", sep = "")
}, warning = hook_lst_bf, message = hook_lst_bf, error = hook_lst_bf)
## empty highlight header since it is not useful any more
set_header(highlight = "")
As you can see, knitr exposes everything to the user. All you need to do is to make sure that these pieces R source and output can be wrapped in proper environments.
Wait, do not copy the code above, because I have already made them into knitr via the function render_listings() with a few tweaks. Here is an example:
- Using knitr with listings
- Rnw source: knitr-listings.Rnw
- LyX source: knitr-listings.lyx
- PDF output: knitr-listings.pdf
One screenshot from the PDF output:

I thank Frank Harrell for the LaTeX style file Sweavel.sty.
More listings options
The listings package has tons of options that you can use, so be sure to read its manual to know its full power. Below is an example to show how to break lines in the error messages, and you can download its the Rnw source. The key is the option breaklines=true.

Donate
As a freelancer (currently working as a contractor) and a dad of three kids, I truly appreciate your donation to support my writing and open-source software development! Your contribution helps me cope with financial uncertainty better, so I can spend more time on producing high-quality content and software. You can make a donation through methods below.
-
Venmo:
@yihui_xie, or Zelle:xie@yihui.name -
Paypal
-
If you have a Paypal account, you can follow the link https://paypal.me/YihuiXie or find me on Paypal via my email
xie@yihui.name. Please choose the payment type as “Family and Friends” (instead of “Goods and Services”) to avoid extra fees. -
If you don’t have Paypal, you may donate through this link via your debit or credit card. Paypal will charge a fee on my side.
-
-
Other ways:
WeChat Pay (微信支付:谢益辉) Alipay (支付宝:谢益辉) 

When sending money, please be sure to add a note “gift” or “donation” if possible, so it won’t be treated as my taxable income but a genuine gift. Needless to say, donation is completely voluntary and I appreciate any amount you can give.
Please feel free to email me if you prefer a different way to give. Thank you very much!
I’ll give back a significant portion of the donations to the open-source community and charities. For the record, I received about $30,000 in total (before tax) in 2024-25, and gave back about $15,000 (after tax).