An open API service indexing awesome lists of open source software.

https://github.com/erictleung/pyblack

RStudio addin to style Python code blocks with black
https://github.com/erictleung/pyblack

black formatting python rstudio rstudio-addin

Last synced: 7 months ago
JSON representation

RStudio addin to style Python code blocks with black

Awesome Lists containing this project

README

          

---
output: github_document
---

```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-",
out.width = "100%"
)
```

# pyblack

[![R-CMD-check](https://github.com/erictleung/pyblack/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/erictleung/pyblack/actions/workflows/R-CMD-check.yaml)
[![Project Type Toy Badge](https://img.shields.io/badge/project%20type-toy-blue)](https://project-types.github.io/#toy)

RStudio addin to style Python code blocks with
[black](https://github.com/psf/black).

![Demo of the pyblack RStudio addin to help format Python code in RMarkdown](man/figures/pyblack.gif)

## Installation

```r
remotes::install_github("erictleung/pyblack")
```

You must have black installed and accessible in your path for this addin to
work.

```bash
pip install black
```

## Usage

This addin supports styling with black by:

- highlighted selected code
- entire active file in RStudio

**For select code**, in your text editor, first highlight the relevant Python
code you wish to format. Then navigate in RStudio to Addins > PYBLACK > Style
selection with black.

**For formatting an entire active document**, in your text editor, have your
cursor in an open document you want to format. Then navigate in RStudio to
Addins > PYBLACK > Style active file with black.

There is a third option available to change indentation from 4 spaces to 2
spaces. This does not require or use black to work.

## Configuration

In your working directory, you can have a `pyproject.toml` file that `black`
will read.

Below is an example `pyproject.toml` file that changes the line-length from the
default of 88 to 80.

```
[tool.black]
line-length = 80
```

Other settings available to change can be found by running `black --help`.

You can read more about this
[here](https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#configuration-format).

## Conditionally apply formatting

There are two ways to tell black to apply formatting to a code block:

1. Use `# fmt: off` before a block of code
2. Use `black = FALSE` in chunk options

For example, black won't format the `custom_formatting` object, but will format
the `black_formatting` object.

```python
# fmt: off
custom_formatting = [
0, 1, 2,
3, 4, 5,
6, 7, 8,
]
# fmt: on
black_formatting = [
0, 1, 2,
3, 4, 5,
6, 7, 8,
]
```

Another way to avoid formatting an entire code block is to set `black = FALSE`
in the code chunk.

````{verbatim}
```{python, black = FALSE}

```
````

## License

MIT