Skip to content

Copy multi-line Python code #65

@joleroi

Description

@joleroi

Situation

I would like to add a copy button to Python code of the following form

Code example
============

.. code-block:: python
        
    >>> import pandas as pd
    >>> data = dict(
    ... movie = ['Rambo', 'Commando', 'Mad Max'],
    ... actor = ['Sylvester Stallone', 'Arnold Schwarzenegger', 'Mel Gibson'],
    ... year = [1982, 1985, 1980]
    ... )
    >>> df = pd.DataFrame(data=data)
    >>> print(df)
          movie                  actor  year
    0     Rambo     Sylvester Stallone  1982
    1  Commando  Arnold Schwarzenegger  1985
    2   Mad Max             Mel Gibson  1980

I added the following to my conf.py

extensions = [
     'sphinx_copybutton',
]

copybutton_prompt_text = ">>> "
copybutton_only_copy_prompt_lines = True

I get the following output, when clicking the copy button in the generated HTML

import pandas as pd
data = dict(
... movie = ['Rambo', 'Commando', 'Mad Max'],
... actor = ['Sylvester Stallone', 'Arnold Schwarzenegger', 'Mel Gibson'],
... year = [1982, 1985, 1980]
... )
df = pd.DataFrame(data=data)
print(df)
      movie                  actor  year
0     Rambo     Sylvester Stallone  1982
1  Commando  Arnold Schwarzenegger  1985
2   Mad Max             Mel Gibson  1980

Problem

As expected the lines starting with >>> are copied and the prompt is removed. But

  • Lines starting with ... are kept as they are. I'm surprised that they aren't removed by the copybutton_only_copy_prompt_lines option. In any case: What I actually want is to treat ... also as prompt, i.e. keep the lines but remove the ... . This might be related to feature request: configurability of copyability #52

  • The output table at the end, is also copied. Again this should not happen with the copybutton_only_copy_prompt_lines option present.

Suggestions

Im not very good at Js but if you guys acknowledge the issue I can make a PR. But if its easy for you, go ahead :)

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions