File tree Expand file tree Collapse file tree
src/cortex-core/src/markdown/table Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -151,6 +151,29 @@ mod tests {
151151 assert ! ( table. column_widths[ 1 ] >= 20 ) ;
152152 }
153153
154+ #[ test]
155+ fn test_column_width_distribution_preserves_available_space ( ) {
156+ let mut builder = TableBuilder :: new ( ) ;
157+ builder. start_header ( ) ;
158+ builder. add_cell ( "A A A" . to_string ( ) ) ;
159+ builder. add_cell ( "B B B" . to_string ( ) ) ;
160+ builder. add_cell ( "C C C" . to_string ( ) ) ;
161+ builder. end_header ( ) ;
162+
163+ builder. start_row ( ) ;
164+ builder. add_cell ( "aa bb cc" . to_string ( ) ) ;
165+ builder. add_cell ( "dd ee ff" . to_string ( ) ) ;
166+ builder. add_cell ( "gg hh ii" . to_string ( ) ) ;
167+ builder. end_row ( ) ;
168+
169+ let mut table = builder. build ( ) ;
170+ let max_width = 21 ;
171+ table. calculate_column_widths ( max_width) ;
172+
173+ // Three columns have 4 border chars and 6 padding chars, leaving 11 content chars.
174+ assert_eq ! ( table. column_widths. iter( ) . sum:: <usize >( ) , 11 ) ;
175+ }
176+
154177 #[ test]
155178 fn test_missing_cells_in_rows ( ) {
156179 let mut builder = TableBuilder :: new ( ) ;
Original file line number Diff line number Diff line change @@ -209,11 +209,35 @@ impl Table {
209209 self . column_widths = min_widths. clone ( ) ;
210210
211211 if pref_extra > 0 {
212+ let mut allocated_total = 0 ;
213+ let mut remainders = Vec :: with_capacity ( num_cols) ;
214+
212215 for i in 0 ..num_cols {
213216 let col_extra = pref_widths[ i] . saturating_sub ( min_widths[ i] ) ;
214- let allocated =
215- ( col_extra as f64 / pref_extra as f64 * extra_space as f64 ) as usize ;
217+ let weighted_extra = col_extra * extra_space;
218+ let allocated = weighted_extra / pref_extra;
219+ let remainder = weighted_extra % pref_extra;
220+
216221 self . column_widths [ i] += allocated;
222+ allocated_total += allocated;
223+
224+ if allocated < col_extra {
225+ remainders. push ( ( i, remainder) ) ;
226+ }
227+ }
228+
229+ let mut remaining = extra_space. saturating_sub ( allocated_total) ;
230+ remainders. sort_by ( |a, b| b. 1 . cmp ( & a. 1 ) . then_with ( || a. 0 . cmp ( & b. 0 ) ) ) ;
231+
232+ for ( i, _) in remainders {
233+ if remaining == 0 {
234+ break ;
235+ }
236+
237+ if self . column_widths [ i] < pref_widths[ i] {
238+ self . column_widths [ i] += 1 ;
239+ remaining -= 1 ;
240+ }
217241 }
218242 }
219243 } else {
You can’t perform that action at this time.
0 commit comments