Skip to content

Global toggle code wrap button #7875

Open

Description

@JPeer264

Have you read the Contributing Guidelines on issues?

Motivation

Code wrap buttons have been implemented: #7036

The thing is that it is a little cumbersome if this needs to be done on each codeblock individually. This proposal is that this setting will be stored globally to set it to the users needs.

Self-service

  • I'd be willing to do some initial work on this proposal myself.

Activity

  1. added
    proposal
    status: needs triage
    on Aug 1, 2022
  2. added
    feature
    and removed
    proposal
    status: needs triage
    on Aug 1, 2022
  3. Josh-Cena commented on Aug 1, 2022

    @Josh-Cena
    Collaborator

    We probably won't add a button (otherwise we need a "user control panel", which may not be a totally bad idea, like how MUI is doing it). But a global option seems worthwhile.

    Why would you want to wrap the code? I've almost never wanted to wrap it.

  4. JPeer264 commented on Aug 1, 2022

    @JPeer264
    ContributorAuthor

    Oh I am sorry. It seems this went sideways. What I meant is when the user toggles one it should toggle all others too (to be clear, I am also not a big fan of wrapping it - but some of our customers are now using the feature as it got shipped with docusaurus).

    Basically only this line would be touched: https://github.com/facebook/docusaurus/blob/main/packages/docusaurus-theme-common/src/hooks/useCodeWordWrap.ts#L61

    E.g.:

    - const [isEnabled, setIsEnabled] = useState(false);
    + const [isEnabled, setIsEnabled] = useLocalstorageState(false);
  5. Josh-Cena commented on Aug 1, 2022

    @Josh-Cena
    Collaborator

    Oh, I see your point. Would you be happy with a theme option that syncs the wrap state between all code blocks?

  6. JPeer264 commented on Aug 1, 2022

    @JPeer264
    ContributorAuthor

    Of course that would be ideal.

  7. slorber commented on Aug 9, 2022

    @slorber
    Collaborator

    Others looking for a similar feature:

    @jaredcbaum in #5468 (comment)

    @jgoux in #7769

    Please help us decide what should be done so that all of you are satisfied ;)

  8. JPeer264 commented on Aug 25, 2022

    @JPeer264
    ContributorAuthor

    I would propose a new theme configuration. I think with these everything should be covered:

    {
      codeBlockOptions: {
        // this identifies if the code block should be wrapped or not on the first page load 
        defaultAppearance: 'default' | 'wrapped'; // default: 'default'
        // if the wrap state should be stored globally or not
        enableWrapSync: boolean; // default: false
        // enables or disables the visual representation of the code wrap
        showWrap: boolean; // default: true
      };
    }
    
  9. jaredcbaum commented on Aug 29, 2022

    @jaredcbaum
    {
        codeBlock: {
            // Option to show copy button
            showCopy: boolean; // default true
    
            // Option to show wrap button
            showWrap: boolean; // default true
    
            // Option to control default wrapping
            defaultWrap: boolean; // default false;
        }
    }
    

    IMHO this would be an ideal config setup for code blocks. Since these options would be in docusaurus.config.js, it can be assumed that these options are global. They could be overridden on a per instance basis by passing options to the CodeBlock component or a per page basis with a frontmatter value.

  10. JPeer264 commented on Aug 29, 2022

    @JPeer264
    ContributorAuthor

    I like that! The only thing I miss is the localStorage/global sync (which was the origin of this issue).

  11. paulboocock commented on Sep 6, 2022

    @paulboocock

    I noticed in #7769 it was suggested that this could be enabled/forced for a single code block. I have the odd code block where it makes sense to have it forced on, or at least enabled by default.

    So this syntax (or similar) would be great for me:

        ```bash wordWrap=true
         ...
        ```
    

    Example: https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/javascript-trackers/javascript-tracker/javascript-tracker-v3/tracker-setup/loading/

    I could also add some linebreaks 🤷

    However, most snippets are far better with word wrap disabled, so I wouldn't really want to change the default for the whole site, or to even remember it page by page.

  12. gtnardy commented on Jun 14, 2023

    @gtnardy
  13. 4 remaining items

  14. tarakta commented on Sep 18, 2023

    @tarakta
  15. lathropcat commented on Sep 18, 2023

    @lathropcat
  16. RoksanaSkrzycka commented on Sep 19, 2023

    @RoksanaSkrzycka
  17. slorber commented on Sep 28, 2023

    @slorber
    Collaborator

    We started working on this in #9349, and a few questions arise because there are orthogonal needs

    • Should we always sync and persist in localStorage at the same time, or are these different features? IE could we sync the setting between code blocks without persisting the last choice, and vice versa?
    • Is sync/persistence opt-in or always enabled?
    • Should sync and/or persistence be enabled on a case-by-case basis, similar to how tabs work?
    • Do we need both a global site setting, and a code block meta-string param
    • If a global and/or meta string value is provided, and a localStorage value exist, what should be the value we use? We have 3 sources available to provide that value and need to figure a rule here.

    As you can see, there are still design elements to discuss.


    On the technical side, there are also important UX details to consider:

    • We need to ensure there's no layout shifts due to the sync when we click on the code wrap button (similar case to tabs we had in the past: the button position shifts and does not stay under user cursor)
    • We need to ensure a good React hydration experience. We don't want code blocks to initially appear with scrollbars and then shift to wrapping, producing layout shifts
  18. lvcarnevalli commented on Jul 13, 2024

    @lvcarnevalli

    Hi everyone, do we have any updates on this 'wordWrap' feature?

  19. benjie commented on Dec 19, 2024

    @benjie

    As a workaround, I wrap the code block in a div with a custom class:

    <div className="wrapcode">
    
    ```
    Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /path/to/graphile.config.ts
    require() of ES modules is not supported.
    require() of /path/to/graphile.config.ts from /path/to/node_modules/graphile-config/dist/loadConfig.js is an ES module file as it is a .ts file whose nearest parent package.json contains "type": "module" which defines all .ts files in that package scope as ES modules.
    Instead change the requiring code to use import(), or remove "type": "module" from /path/to/package.json.
    ```
    
    </div>

    and added the wrapcode class to my src/css/custom.css:

    .wrapcode code {
      white-space: pre-wrap;
    }
  20. added 2 commits that reference this issue on Dec 19, 2024
  21. ivancheban commented on Dec 19, 2024

    @ivancheban
    Contributor

    I see that now Docusaurus code blocks have this code wrapping feature out-of-the-box: there's a Toggle word wrap button in the code blocks with long lines of code. Please close this issue.
    image

  22. aMacDawg commented on Jan 28, 2025

    @aMacDawg

    @ivancheban yes, the spirit of this ticket as I understand (and I share need the for fwiw) is to enable a way (most likely some kind of param passed when defining the markdown body itself) to have that Toggle word wrap on by default

    There is no current known way to do this without writing a custom css class like @benjie demo'd above, ergo ticket should stay OPEN imo

  23. ZenaMel commented on May 9, 2025

    @ZenaMel
    Contributor

    We would also benefit from at least a meta tag, e.g., "wordWrap=true" or IMO better: "wrap=true" or just "wrap", as the odd codeBlock (mostly one-liner scripts) will be more readable that way. I don't think we personally would need a global config option for this.

  24. ZenaMel commented on May 13, 2025

    @ZenaMel
    Contributor

    If you want to implement a bare-bones, block-by-block toggleable default wrap attribute for code blocks right now while this is being worked on by the team:

    Syntax this will allow:

    ```js wrap
    ...
    ```

    1. Swizzle the CodeBlock component:
      npx docusaurus swizzle @docusaurus/theme-classic CodeBlock
      
    2. Modify the src/theme/CodeBlock/Content/String.js file so that the final code looks like this:
    import React, { useEffect, useMemo } from 'react';
    import clsx from 'clsx';
    import {useThemeConfig, usePrismTheme} from '@docusaurus/theme-common';
    import {
      parseCodeBlockTitle,
      parseLanguage,
      parseLines,
      containsLineNumbers,
      useCodeWordWrap,
    } from '@docusaurus/theme-common/internal';
    import {Highlight} from 'prism-react-renderer';
    import Line from '@theme/CodeBlock/Line';
    import CopyButton from '@theme/CodeBlock/CopyButton';
    import WordWrapButton from '@theme/CodeBlock/WordWrapButton';
    import Container from '@theme/CodeBlock/Container';
    import styles from './styles.module.css';
    // Prism languages are always lowercase
    // We want to fail-safe and allow both "php" and "PHP"
    // See https://github.com/facebook/docusaurus/issues/9012
    function normalizeLanguage(language) {
      return language?.toLowerCase();
    }
    export default function CodeBlockString({
      children,
      className: blockClassName = '',
      metastring,
      title: titleProp,
      showLineNumbers: showLineNumbersProp,
      language: languageProp,
    }) {
      const {
        prism: {defaultLanguage, magicComments},
      } = useThemeConfig();
      const language = normalizeLanguage(
        languageProp ?? parseLanguage(blockClassName) ?? defaultLanguage,
      );
      const prismTheme = usePrismTheme();
      const wordWrap = useCodeWordWrap();
      
      // Check if wrap is specified in metastring or className
      const shouldWrapByDefault = useMemo(() => {
        // Check metastring for 'wrap'
        if (metastring?.includes('wrap')) {
          return true;
        }
        
        // Check if language has 'wrap' suffix (e.g., bash-wrap, js-wrap)
        const languageMatch = blockClassName?.match(/language-(\w+)-?wrap/);
        if (languageMatch) {
          return true;
        }
        
        return false;
      }, [metastring, blockClassName]);
      
      // Apply word wrap after initial render if needed
      useEffect(() => {
        if (shouldWrapByDefault && !wordWrap.isEnabled) {
          wordWrap.toggle();
        }
      }, [shouldWrapByDefault, wordWrap]);
    
      // We still parse the metastring in case we want to support more syntax in the
      // future. Note that MDX doesn't strip quotes when parsing metastring:
      // "title=\"xyz\"" => title: "\"xyz\""
      const title = parseCodeBlockTitle(metastring) || titleProp;
      const {lineClassNames, code} = parseLines(children, {
        metastring,
        language,
        magicComments,
      });
      const showLineNumbers =
        showLineNumbersProp ?? containsLineNumbers(metastring);
      return (
        <Container
          as="div"
          className={clsx(
            blockClassName,
            language &&
              !blockClassName.includes(`language-${language}`) &&
              `language-${language}`,
          )}>
          {title && <div className={styles.codeBlockTitle}>{title}</div>}
          <div className={styles.codeBlockContent}>
            <Highlight theme={prismTheme} code={code} language={language ?? 'text'}>
              {({className, style, tokens, getLineProps, getTokenProps}) => (
                <pre
                  /* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */
                  tabIndex={0}
                  ref={wordWrap.codeBlockRef}
                  className={clsx(className, styles.codeBlock, 'thin-scrollbar')}
                  style={style}>
                  <code
                    className={clsx(
                      styles.codeBlockLines,
                      showLineNumbers && styles.codeBlockLinesWithNumbering,
                    )}>
                    {tokens.map((line, i) => (
                      <Line
                        key={i}
                        line={line}
                        getLineProps={getLineProps}
                        getTokenProps={getTokenProps}
                        classNames={lineClassNames[i]}
                        showLineNumbers={showLineNumbers}
                      />
                    ))}
                  </code>
                </pre>
              )}
            </Highlight>
            <div className={styles.buttonGroup}>
              {(wordWrap.isEnabled || wordWrap.isCodeScrollable) && (
                <WordWrapButton
                  className={styles.codeButton}
                  onClick={() => wordWrap.toggle()}
                  isEnabled={wordWrap.isEnabled}
                />
              )}
              <CopyButton className={styles.codeButton} code={code} />
            </div>
          </div>
        </Container>
      );
    }
    1. Now you can use the wrap modifier in your markdown code blocks:

    ```bash wrap
    This command will be word-wrapped by default
    some_very_long_command --with-many-parameters --and-options
    ...
    ```

    This implementation:

    • Doesn't modify any Docusaurus internals
    • Is (mostly) upgrade-friendly
    • Still allows users to toggle word wrap on/off with the button

    Do note that this probably wouldn't be the way to go for the official implementation. Also note that this approach might have your content "jump" if you've got any codeblocks over the fold.

  25. sakurawald commented on Oct 15, 2025

    @sakurawald

    It's a surprise that the "wordWrap=true" option didn't exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions