You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Ignore linebreaks between Chinese/Japanese characters in source code #792
cjkChinese, Japanese, Korean typography.feature requestNew feature or requestsyntaxAbout syntax, parsing, etc.textRelated to the text category, which is all about text handling, shaping, etc.
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:
Eliminate spaces between CJK characters in source code.
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.
Reacted by Tan Long, Caleb Maclennan, 也吏, Zhan Rongrui, Gaoyang Zhang, Sora Shu, El Pin Al, Matsu, littzhch, 动量子 and 54 more
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).
Reacted by Matsu, Norimasa Takana, Caleb Maclennan, CUI CHUAN, Chen Linxuan, Ming-Long Huang and Yicheng Liu
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.
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.
#letcjkre= regex("\s*(\p{Han}+)\s*")
#showcjkre: it=>it.text.match(cjkre).captures.at(0)
= 你好,我是 你的朋友。
“你好” check测试:
hello, this is a test!
世界 你好,
我很好。
Reacted by Juntong Chen, Kevin Stephen, Savio Mak and rayfiyo
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.
The CTeX package bundle implements common Chinese typesetting practices. It determines how LaTeX compilers interpret spaces and \n.
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
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⟩.
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.)
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.
#letcjkre= regex("\s*(\p{Han}+)\s*")
#showcjkre: 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.
#letcjk-char= "[\p{Han},。;:!?‘’“”()「」【】…—]"#letcjk-re= regex("\s*("+cjk-char+")\s*")
#showcjk-re: it=>it.text.match(cjk-re).captures.at(0)
#show: rest=> {
letends-with-cjk= it=> {
it!=noneandit.has("text") andit.text.ends-with(regex(cjk-char))
}
letlast-item= noneforiteminrest.children {
ifitem== [ ] andends-with-cjk(last-item) {
item= []
}
last-item=itemitem
}
}
= 你好,我是 你的 朋友。
“你好” check测试:
hello, world! this is a test!
this
is good.
世界
你 好 啊,
我很好。
which gets rendered as:
你好,我是你的朋友。
“你好”check 测试:hello, world! this is a test! 世界你好啊,我很好。
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.
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
// 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
letmut 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
#setpage(height: auto)
#settext(lang: "zh", region: "CN", font: "Noto Serif CJK is fantastic, but spaces are more visible between tofu")
汉字 分词
技术 English Latin
Continue 汉字
And
孔乙己
鲁镇的酒店的格局,是和别处不同的:
都是当街一个曲尺形的大柜台,
柜里面预备着热水,可以随时温酒。
鲁镇的酒店的格局,是和别处不同的: //
都是当街一个曲尺形的大柜台, //
柜里面预备着热水,可以随时温酒。
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.
changed the title [-]Ignore linebreaks between CJK characters in source code[/-][+]Ignore linebreaks between CJ characters in source code[/+]on Dec 1, 2025
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.
changed the title [-]Ignore linebreaks between CJ characters in source code[/-][+]Ignore linebreaks between Chinese/Japanese characters in source code[/+]on Dec 2, 2025
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.
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.
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.
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.
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.
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.
cjkChinese, Japanese, Korean typography.feature requestNew feature or requestsyntaxAbout syntax, parsing, etc.textRelated to the text category, which is all about text handling, shaping, etc.
Activity
Karmac commentedon May 12, 2023
+1 for the trailing comment
That would solve my issue at #1173 and give users more control over line breaks.
zrr1999 commentedon May 16, 2023
+1
littzhch commentedon Sep 20, 2023
Is there any workaround to this problem for now?
Zjl37 commentedon Oct 6, 2023
+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
langorscriptparameter 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).
bb010g commentedon Dec 20, 2023
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,
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:
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.
laurmaedje commentedon Jul 15, 2024
Somewhat related: #710
admk commentedon Aug 21, 2024
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.
YDX-2147483647 commentedon Aug 22, 2024
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.
The CTeX package bundle implements common Chinese typesetting practices. It determines how LaTeX compilers interpret spaces and
\n.CTeX provides an option to control whether to keep spaces after Han characters in the generated PDF.
An example
main.tex: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 Latintrue: always keep⇒
汉字 分词 技术 English LatinIn this case, we need to add
%before\n. (%in LaTeX =//in typst) Otherwise,\nwill generate an extra space, because LaTeX compiler takes a single\nas a space.false: always remove⇒
汉字分词技术English LatinCTeX use different packages for different LaTeX compilers. Consequently, the option is not fully supported by all compilers…
auto(default)truefalse(Many Chinese templates only support XeLaTeX and LuaLaTeX.)
References:
space = ⟨true|false|auto⟩.CJKspace = ⟨true|false⟩.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)
字+\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
Results:
xelatex +
\documentclass{article}(Those are U+FFFF None characters, but GitHub might convert them to U+FFFD.)
xelatex +
\documentclass{article}+\usepackage{xeCJK}lualatex +
\documentclass{article}(Those are U+FFFD Replacement characters.)
lualatex +
\documentclass{article}+\usepackage{luatexja}admk commentedon Aug 26, 2024
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.
which gets rendered as:
YDX-2147483647 commentedon Aug 26, 2024
Hi @admk! As described in #710,
contentis not well traverseable.For example,
#set text(lang: "zh")will createstyled(instead ofsequence), breaking your#show: rest => …rule.It might be possible to inspect
sequence/styledand traverse thecontent, but it will be a fragile hack…https://discord.com/channels/1054443721975922748/1088371867913572452/1205542340144537651
laurmaedje commentedon Aug 26, 2024
Indeed, in particular with more usage of
context(which I believe will only grow). See also: #4745YDX-2147483647 commentedon Sep 14, 2024
Well, it is not so difficult to remove spaces that generated by a
\nafter 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
typst/crates/typst-syntax/src/ast.rs
Lines 67 to 80 in d48293f
to
and
use unicode_script::{Script, UnicodeScript};An example
Side effects
Only one test failed, and it is expected.
Future work
If this is the right way to go,
',' | '。' | ':'should be replaced byis_cjk_punctuation/is_cjk_left_aligned_punctuation/… heretypst/crates/typst/src/layout/inline/shaping.rs
Line 114 in d48293f
#set text(ignore-???-newline: false), as in Automatically add spacing between CJK and Latin characters #2334 .14 remaining items
neruthes commentedon Sep 3, 2025
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:
#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:
yhx-12243 commentedon Oct 10, 2025
For this type of bypass, you can use
123#{ }789FYI. It's not very elegant, though.
At least I wish the LaTeX-like “%” technique can be worked here:
123// 789isuffix commentedon Oct 10, 2025
Note that block comments (
/**/) would also work:account-login commentedon Oct 25, 2025
For people converting from pandoc markdown: you can use
pandoc -f markdown+east_asian_line_breaks --wrap=noneto remove line breaks.tats-u commentedon Dec 1, 2025
Korean should be excluded:
Firefox and Prettier has already done.
[-]Ignore linebreaks between CJK characters in source code[/-][+]Ignore linebreaks between CJ characters in source code[/+]Andrew15-5 commentedon Dec 1, 2025
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.
[-]Ignore linebreaks between CJ characters in source code[/-][+]Ignore linebreaks between Chinese/Japanese characters in source code[/+]kong13661 commentedon Dec 24, 2025
I think the space between reference and cjk word should be ignored.
For example, the reference name is
ref.测@ref试will useref试as the reference name, so I have to use测@ref 试. But this will induce a space between the reference and 试. This should be ignored.black-desk commentedon Dec 24, 2025
try
#ref(<foo>)YDX-2147483647 commentedon Dec 24, 2025
The quick way:
测@ref\试(
测@ref;试does not work as expected)Not always.
If
@refgenerates文献 [1], then the space after@ref…见文献 [1]。文献 [1] 指出Edit on 2025-12-30
For the record, isuffix started a thread in Discord CJK channel on 2025-12-25.
kong13661 commentedon Jan 4, 2026
测@ref\试is a good idea. But I think the second condition should also be trimmed:文献 [1] 指出The space should controled by the cjk space, other than insert a space character.
rayfiyo commentedon Feb 19, 2026
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
termsandplace—are not yet supported at this stage.https://typst.app/universe/package/cjk-unbreak
cjk-spacer
This package is implemented using
showrules targetingtext. As a result, it is less dependent on specific functions or elements, and in principle can suppress unnecessary spaces between CJK characters for alltextnodes.https://typst.app/universe/package/cjk-spacer/
Explanation (in Japanese):
https://zenn.dev/akamimi/articles/04d28e2f4fd602