Skip to content

Ignore linebreaks between Chinese/Japanese characters in source code #792

Closed

Description

@peng1999

Typst currently support breaking a paragraph into several consecutive lines in source code, without introduce a newline in result PDF. The single newline in source code will just become a space. However, when working with scripts that do not using spaces between words, like Chinese and Japanese, we often not want to have the newline, nor the space.

In a paragraph like this:

中文
测试

In Chinese context, the most sensible result is 中文测试, without any spaces and newlines.

I propose implementing the following features in typst:

  1. Eliminate spaces between CJK characters in source code.
  2. Let trailing comment consume a linebreak in source code.
    This is because sometimes we have a inline frame and CJK detect will not work, so we need an opt-in method. I think the changed behavior can be minimal, comments will consume new line only if it has no space before it.
    For example, this code
    abc //
    def
    
    becomes abc def
    and
    abc//
    def
    
    becomes abcdef.
    Latin users often use the former one so they will not be affected.

Activity

  1. added
    feature request
    syntax
    text
    on Apr 17, 2023
  2. Karmac commented on May 12, 2023

    @Karmac

    +1 for the trailing comment

    That would solve my issue at #1173 and give users more control over line breaks.

  3. zrr1999 commented on May 16, 2023

    @zrr1999
    Contributor

    +1

  4. littzhch commented on Sep 20, 2023

    @littzhch

    Is there any workaround to this problem for now?

  5. Zjl37 commented on Oct 6, 2023

    @Zjl37

    +1

    Yes, this feature is very desirable in East Asian context, especially when one wants to manually wrap lines in source file.

    However, instead of removing space between CJK characters, I propose disabling automatic space insertion at linebreaks in source code depending on the lang or script parameter of the current text.

    As for the syntax of opting-out this automatic space occasionally, I think this is another topic that needs further discussion (maybe in another issue).

  6. bb010g commented on Dec 20, 2023

    @bb010g

    If comments are going to consume a linebreak, I'd also like them to consume space at the beginning of the next line. That way,

    #repr([//
      abc //
      // actual comment
      def//
    ])

    evaluates to [abc def] and not [([ ], [abc], [ ], [ ], [ ], [def], [ ])].

    I know that looks like ugly TeX, but you can't use block syntax for this purpose currently:

    #repr({
      [abc ]
      // actual comment
      [def]
    })

    evaluates to [([abc], [ ], [def])], and you additionally have to deal with the introduction of scopes you may not want (e.g. because they throw off a #set). Variants of {} & [] that don't introduce new scopes would be a possible solution to this, but the result would still be noisy:

    /{
      /[中文]/
      /[测试]/
    }/

    for the original example. I still think that syntax would be really useful for scripting.

  7. laurmaedje commented on Jul 15, 2024

    @laurmaedje
    Member

    Somewhat related: #710

  8. admk commented on Aug 21, 2024

    @admk

    Also may I suggest that spaces added between CJK characters should not be rendered. This behavior is consistent with XeLaTeX and will make vim-based motion a lot easier.

    Update: I've the following hack that achieves this behavior in most cases, though it struggles with spaces around CJK punctuation and line breaks. I'm unsure how to resolve this issue, which I believe may be related to #86.

    #let cjkre = regex("\s*(\p{Han}+)\s*")
    #show cjkre: it => it.text.match(cjkre).captures.at(0)
    
    = 你好,我是 你的朋友。
    
    “你好” check测试:
    hello, this is a test!
    世界 你好,
    我很好。
  9. YDX-2147483647 commented on Aug 22, 2024

    @YDX-2147483647
    Contributor

    Well, many behaviors in LaTeX are only documented in Chinese, so let me explain here.

    What it is like in LaTeX

    Linbreaks between Han characters

    This section was wrote in August 2024.

    1. The CTeX package bundle implements common Chinese typesetting practices. It determines how LaTeX compilers interpret spaces and \n.

    2. CTeX provides an option to control whether to keep spaces after Han characters in the generated PDF.

      An example main.tex:

      汉字 分词
      技术 English Latin
      
      • auto (default): remove the space if it is followed by another Han character; keep it if not.

        ⇒ 汉字分词技术 English Latin

      • (fallback): remove spaces generated by \n, but keep other literal spaces

        ⇒ 汉字 分词技术 English Latin

      • true: always keep

        ⇒ 汉字 分词 技术 English Latin

        In this case, we need to add % before \n. (% in LaTeX = // in typst) Otherwise, \n will generate an extra space, because LaTeX compiler takes a single \n as a space.

      • false: always remove

        ⇒ 汉字分词技术English Latin

    3. CTeX use different packages for different LaTeX compilers. Consequently, the option is not fully supported by all compilers…

      auto (default) (fallback) true false
      XeLaTeX ✅ ❌ ✅ ❌
      LuaLaTeX ❌ ✅ ❌ ❌
      upLaTeX ❌ ✅ ❌ ❌
      (pdf)LaTeX ✅ ❌ ✅ ✅

      (Many Chinese templates only support XeLaTeX and LuaLaTeX.)

    References:

    • CTeX doc (Chinese), §5.3 space = ⟨true|false|auto⟩.
    • xeCJK doc (Chinese), §3.1CJKspace = ⟨true|false⟩.
    • Overleaf documents (English): Chinese, Japanese, Korean.
    • LuaTeX-ja doc (Japanese and English), §1.2 Linebreak after a Japanese character and Spaces related to Japanese characters, and §15 Linebreak after a Japanese Character.

    Linbreaks next to CJ punctuation marks

    This section is added in November 2025, after we noticed the problem in #7350 (comment). You might want to read that thread before continuing here.

    CTeX uses xeCJK for xelatex and luatexja for luatexja. (Yes, luatexja is developed by Japanese and also used by Chinese.)
    They also treat linebreaks next to “” differently.

    (☑️ = space, ❌ = nothing)

    Combination bare latex xeCJK luatexja
    字 + \n + 字 ☑️ ❌ ❌
    , + \n + 字/“ ☑️ ❌ ❌
    字 + \n + “ ☑️ ❌ ☑️
    ” + \n + 字/A/“ ☑️ ❌ ☑️
    A/, + \n + A/“ ☑️ ☑️ ☑️

    Nevertheless, this might merely be a technical limitation rather than an intentionally design — the core latex/xelatex/lualatex is not as open for change as Typst.

    Test main.tex file and raw results
    \documentclass{article}
    \usepackage{luatexja}
    % Or \usepackage{xeCJK}
    
    \begin{document}
    
    START
    
    一
    二,
    三
    “四,
    “五”
    “六”
    七。
    
    a
    b,
    c
    “d,
    “e”
    “f”
    g.
    
    END
    
    \end{document}

    Results:

    • xelatex + \documentclass{article}

      � �� � “�� “�” “�” ��
      a b, c “d, “e” “f” g.
      

      (Those are U+FFFF None characters, but GitHub might convert them to U+FFFD.)

    • xelatex + \documentclass{article} + \usepackage{xeCJK}

      一二,三“四,“五”“六”七。
      a b, c “d, “e”“f”g.
      
    • lualatex + \documentclass{article}

      � �� � “�� “�” “�” ��
      a b, c “d, “e” “f” g.
      

      (Those are U+FFFD Replacement characters.)

    • lualatex + \documentclass{article} + \usepackage{luatexja}

      一二,三 “四,“五” “六” 七。
      a b, c “d, “e” “f” g.
      
  10. admk commented on Aug 26, 2024

    @admk

    Also may I suggest that spaces added between CJK characters should not be rendered. This behavior is consistent with XeLaTeX and will make vim-based motion a lot easier.

    Update: I've the following hack that achieves this behavior in most cases, though it struggles with spaces around CJK punctuation and line breaks. I'm unsure how to resolve this issue, which I believe may be related to #86.

    #let cjkre = regex("\s*(\p{Han}+)\s*")
    #show cjkre: it => it.text.match(cjkre).captures.at(0)
    
    = 你好,我是 你的朋友。
    
    “你好” check测试:
    hello, this is a test!
    世界 你好,
    我很好。

    Using the idea from #1173, I’ve made some changes that seem to handle both line breaks and spaces around CJK characters pretty well. I'm still new to typst and haven’t tested it beyond this example yet, though.

    #let cjk-char = "[\p{Han},。;:!?‘’“”()「」【】…—]"
    #let cjk-re = regex("\s*(" + cjk-char + ")\s*")
    #show cjk-re: it => it.text.match(cjk-re).captures.at(0)
    #show: rest => {
      let ends-with-cjk = it => {
        it != none and it.has("text") and it.text.ends-with(regex(cjk-char))
      }
      let last-item = none
      for item in rest.children {
        if item == [ ] and ends-with-cjk(last-item) {
          item = []
        }
        last-item = item
        item
      }
    }
    
    = 你好,我是 你的 朋友。
    
    “你好” check测试:
    hello, world! this is a test!
    this
    is good.
    世界
    你 好              啊,
    我很好。

    which gets rendered as:

    你好,我是你的朋友。
    
     “你好”check 测试:hello, world! this is a test! 世界你好啊,我很好。 
    
  11. YDX-2147483647 commented on Aug 26, 2024

    @YDX-2147483647
    Contributor

    Hi @admk! As described in #710, content is not well traverseable.

    For example, #set text(lang: "zh") will create styled (instead of sequence), breaking your #show: rest => … rule.

    It might be possible to inspect sequence/styled and traverse the content, but it will be a fragile hack…

    laurmaedje: this wasn't really an intended use case, which is also why they aren't publicly accessible as a global.
    This might change with the type rework. I'm considering to make them properly public then.

    https://discord.com/channels/1054443721975922748/1088371867913572452/1205542340144537651

  12. laurmaedje commented on Aug 26, 2024

    @laurmaedje
    Member

    Indeed, in particular with more usage ofcontext (which I believe will only grow). See also: #4745

  13. YDX-2147483647 commented on Sep 14, 2024

    @YDX-2147483647
    Contributor

    Well, it is not so difficult to remove spaces that generated by a \n after a Han character… If this behaviour is accepted, maybe I can organize it into a PR.

    Implementation

    The “(fallback)” behaviour mentioned in #792 (comment) can be implemented by changing the function

    /// The expressions.
    pub fn exprs(self) -> impl DoubleEndedIterator<Item = Expr<'a>> {
    let mut was_stmt = false;
    self.0
    .children()
    .filter(move |node| {
    // Ignore newline directly after statements without semicolons.
    let kind = node.kind();
    let keep = !was_stmt || node.kind() != SyntaxKind::Space;
    was_stmt = kind.is_stmt();
    keep
    })
    .filter_map(Expr::cast_with_space)
    }

    to

            let mut could_ignore = false;
            self.0
                .children()
                .filter(move |node| {
                    let kind = node.kind();
                    // Ignore newline if directly after…
                    let keep = !could_ignore || kind != SyntaxKind::Space;
                    // …statements without semicolons,
                    could_ignore = kind.is_stmt()
                    // or texts ended with a Han character.
                    || (kind == SyntaxKind::Text
                            && node.text().ends_with(|c: char| {
                                matches!(c.script(), Script::Han)
                                    || matches!(c, ',' | '。' | ':') // and other Chinese punctuations
                            }));
                    keep
                })
                .filter_map(Expr::cast_with_space)

    and use unicode_script::{Script, UnicodeScript};

    An example

    #set page(height: auto)
    #set text(lang: "zh", region: "CN", font: "Noto Serif CJK is fantastic, but spaces are more visible between tofu")
    
    汉字 分词
    技术 English Latin
    Continue 汉字 
    And
    孔乙己
    
    鲁镇的酒店的格局,是和别处不同的:
    都是当街一个曲尺形的大柜台,
    柜里面预备着热水,可以随时温酒。
    
    鲁镇的酒店的格局,是和别处不同的: //
    都是当街一个曲尺形的大柜台, //
    柜里面预备着热水,可以随时温酒。

    图片

    Side effects

    Only one test failed, and it is expected.

    ❌ text-chinese-basic (tests/suite/layout/inline/cjk.typ:4)
      mismatched rendering
        live      | tests/store/render/text-chinese-basic.png
        ref       | tests/ref/text-chinese-basic.png
    2225 passed, 1 failed, 0 skipped
    

    图片

    Future work

    If this is the right way to go,

  14. 14 remaining items

  15. added
    cjk
    on Feb 10, 2025
  16. neruthes commented on Sep 3, 2025

    @neruthes

    I would like to mention \frenchspacing. Without that command, LaTeX would treat interword glues differently, making it wider after a full stop character ("."). This simple tradition revels that whitespace characters can carry deferent semantic nuances at the cost of possibly working wrong with "U.S. xxx" text pieces. One familiar with Unicode would also know full-width space,  , zero-width space, etc.

    A convenient adaptation to traditions is to allow suppressing implicit whitespace at all by ending a line of source code with "//" like how we always do in LaTeX ("%"). This approach conforms to the existing practice and allows everyone to migrate to Typst smoothly.

    My full vision has 2 features:

    • Different white spaces can be manually inserted as "#sym.whitespace", "#sym.longinterwordwhitespace", "#sym.fullwidthwhitespace", etc.
    • A global "assumptions" object can be modified at runtime that determines the culture-sensitive, localized assumptions, like, whether src LF should be interpreted as dst whitespace via "
      #assumptions.implicit_whitespace = "ignore".

    BTW I wish to have xeCJK flags adopted exactly as-is. They are good enough.

    At this moment, here are my workarounds:

    123#"
    ".slice(0,0);789
    #let nolf() = {}
    123#nolf(
    )789
  17. yhx-12243 commented on Oct 10, 2025

    @yhx-12243

    At this moment, here are my workarounds:

    123#"
    ".slice(0,0);789
    #let nolf() = {}
    123#nolf(
    )789

    For this type of bypass, you can use

    123#{
    }789

    FYI. It's not very elegant, though.

    At least I wish the LaTeX-like “%” technique can be worked here:

    123//
    789
  18. isuffix commented on Oct 10, 2025

    @isuffix
    Collaborator

    Note that block comments (/**/) would also work:

    123/*
    */456
    
  19. account-login commented on Oct 25, 2025

    @account-login

    For people converting from pandoc markdown: you can use pandoc -f markdown+east_asian_line_breaks --wrap=none to remove line breaks.

  20. tats-u commented on Dec 1, 2025

    @tats-u

    Korean should be excluded:

    Firefox and Prettier has already done.

  21. changed the title [-]Ignore linebreaks between CJK characters in source code[/-] [+]Ignore linebreaks between CJ characters in source code[/+] on Dec 1, 2025
  22. Andrew15-5 commented on Dec 1, 2025

    @Andrew15-5
    Contributor

    It's better to write Chinese and Japanese in full, because CJ is not a standard contraction like CJK is. I was surprised to see a CJ reference in the issue tracker, only to realize it's just CJK without Korean.

  23. changed the title [-]Ignore linebreaks between CJ characters in source code[/-] [+]Ignore linebreaks between Chinese/Japanese characters in source code[/+] on Dec 2, 2025
  24. kong13661 commented on Dec 24, 2025

    @kong13661

    I think the space between reference and cjk word should be ignored.

    For example, the reference name is ref. 测@ref试 will use ref试 as the reference name, so I have to use 测@ref 试. But this will induce a space between the reference and 试. This should be ignored.

  25. black-desk commented on Dec 24, 2025

    @black-desk

    I think the space between reference and cjk word should be ignored.

    For example, the reference name is ref. 测@ref试 will use ref试 as the reference name, so I have to use 测@ref 试. But this will induce a space between the reference and 试. This should be ignored.

    try #ref(<foo>)

  26. YDX-2147483647 commented on Dec 24, 2025

    @YDX-2147483647
    Contributor

    The quick way: 测@ref\试

    (测@ref;试 does not work as expected)

    the space between reference and cjk word should be ignored.

    Not always.
    If @ref generates 文献 [1], then the space after @ref…

    • …should be trimmed if it is 见文献 [1]。
    • …should not be trimmed if it is 文献 [1] 指出

    Edit on 2025-12-30

    For the record, isuffix started a thread in Discord CJK channel on 2025-12-25.

    In #7350, the general implementation of the feature should not require much more discussion to finish and I encourage you (laurmaedje) to review it.

    But based on discussions in the issue and by the CSS Working Group from 2018 to 2020 (337, 4992, 5017, 5086) there appears to be a near endless depth of complexity in specifying the is_space_discarding function. I find this complexity worth discussion, but I don't think it's worth delaying the ergonomic improvements for Chinese and Japanese writers.

    This reminds me of the reasons that the Codex crate was created: to make space for defining properties with in-depth discussion that can iterate separately from Typst.

    So I'd like to propose that we separate the is_space_discarding function into a separate crate like Codex. Then we can merge this change and make the feature available now, but still iterate on edge cases until we reach agreement. It would also allow others to depend on the crate or use it as a reference.

    …

  27. kong13661 commented on Jan 4, 2026

    @kong13661

    The quick way: 测@ref\试

    (测@ref;试 does not work as expected)

    the space between reference and cjk word should be ignored.

    Not always. If @ref generates 文献 [1], then the space after @ref…

    • …should be trimmed if it is 见文献 [1]。
    • …should not be trimmed if it is 文献 [1] 指出

    Edit on 2025-12-30

    For the record, isuffix started a thread in Discord CJK channel on 2025-12-25.

    In #7350, the general implementation of the feature should not require much more discussion to finish and I encourage you (laurmaedje) to review it.
    But based on discussions in the issue and by the CSS Working Group from 2018 to 2020 (337, 4992, 5017, 5086) there appears to be a near endless depth of complexity in specifying the is_space_discarding function. I find this complexity worth discussion, but I don't think it's worth delaying the ergonomic improvements for Chinese and Japanese writers.
    This reminds me of the reasons that the Codex crate was created: to make space for defining properties with in-depth discussion that can iterate separately from Typst.
    So I'd like to propose that we separate the is_space_discarding function into a separate crate like Codex. Then we can merge this change and make the feature available now, but still iterate on edge cases until we reach agreement. It would also allow others to depend on the crate or use it as a reference.
    …

    测@ref\试 is a good idea. But I think the second condition should also be trimmed:

    • …should not be trimmed if it is 文献 [1] 指出

    The space should controled by the cjk space, other than insert a space character.

  28. rayfiyo commented on Feb 19, 2026

    @rayfiyo

    As a temporary workaround for this issue, I believe the following two Typst Universe packages are currently viable options.

    I hope this helps anyone looking for a workaround.

    cjk-unbreak

    This package traverses Typst’s document abstract syntax tree (AST) in a relatively orthodox and comprehensive manner to remove unnecessary spaces between CJK characters. However, due to the implementation complexity, some functions and elements—such as terms and place—are not yet supported at this stage.

    https://typst.app/universe/package/cjk-unbreak

    cjk-spacer

    This package is implemented using show rules targeting text. As a result, it is less dependent on specific functions or elements, and in principle can suppress unnecessary spaces between CJK characters for all text nodes.

    https://typst.app/universe/package/cjk-spacer/

    Explanation (in Japanese):
    https://zenn.dev/akamimi/articles/04d28e2f4fd602

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

    cjkfeature requestsyntaxtext

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions