@@ -39,17 +39,32 @@ void applyParagraphSpacingAfter(NSMutableAttributedString *output, NSUInteger st
3939 [output addAttribute: NSParagraphStyleAttributeName value: style range: range];
4040}
4141
42- void applyParagraphSpacingBefore (NSMutableAttributedString *output, NSRange range, CGFloat marginTop)
42+ NSUInteger applyParagraphSpacingBefore (NSMutableAttributedString *output, NSRange range, CGFloat marginTop)
4343{
44- if (marginTop <= 0 ) {
45- return ;
46- }
44+ if (marginTop <= 0 || range.location == 0 )
45+ return 0 ;
4746
48- // Note: paragraphSpacingBefore does not work at index 0 in TextKit.
49- // Leading spacing for the first element is handled by renderers via applyBlockSpacingBefore.
50- NSMutableParagraphStyle *style = getOrCreateParagraphStyle (output, range.location );
51- style.paragraphSpacingBefore = marginTop;
52- [output addAttribute: NSParagraphStyleAttributeName value: style range: range];
47+ NSUInteger prevIdx = range.location - 1 ;
48+ if ([output.string characterAtIndex: prevIdx] != ' \n ' )
49+ return 0 ;
50+
51+ NSParagraphStyle *prevStyle = [output attribute: NSParagraphStyleAttributeName atIndex: prevIdx effectiveRange: NULL ];
52+
53+ CGFloat prevMarginBottom = prevStyle.paragraphSpacing ;
54+ if (prevMarginBottom >= marginTop)
55+ return 0 ;
56+
57+ CGFloat extraGap = marginTop - prevMarginBottom;
58+
59+ NSMutableParagraphStyle *spacerStyle = [kBlockSpacerTemplate mutableCopy ];
60+ spacerStyle.baseWritingDirection = currentWritingDirection ();
61+ spacerStyle.paragraphSpacing = MAX (0 , extraGap - 1.0 );
62+
63+ NSDictionary *attrs = @{NSParagraphStyleAttributeName : spacerStyle};
64+ NSAttributedString *spacer = [[NSAttributedString alloc ] initWithString: @" \n " attributes: attrs];
65+
66+ [output insertAttributedString: spacer atIndex: range.location];
67+ return 1 ;
5368}
5469
5570NSUInteger applyBlockSpacingBefore (NSMutableAttributedString *output, NSUInteger insertionPoint, CGFloat marginTop)
0 commit comments