diff --git a/R/rules-line-break.R b/R/rules-line-break.R index a13c11316..b3e56bbcd 100644 --- a/R/rules-line-break.R +++ b/R/rules-line-break.R @@ -136,3 +136,33 @@ remove_line_break_in_empty_fun_call <- function(pd) { } pd } + +mk_add_line_break_at_pos_id <- function(ids) { + ids <- ids + + function(pd_flat){ + min_child_ids <- sapply(seq_len(nrow(pd_flat)), function(i){ + row <- pd_flat[i,] + m <- row$pos_id + while(!row$terminal){ + row <- row$child[[1]][1,] + m <- min(m, row$pos_id) + } + m + }) + + max_child_ids <- sapply(seq_len(nrow(pd_flat)), function(i){ + row <- pd_flat[i,] + m <- row$pos_id + while(!row$terminal){ + row <- row$child[[1]][nrow(row$child[[1]]),] + m <- max(m, row$pos_id) + } + m + }) + + nls <- apply(cbind(min_child_ids, max_child_ids), 1 , function(x) sum(ids >= x[1] & ids <= x[2])) + pd_flat$lag_newlines <- pd_flat$lag_newlines + nls + pd_flat + } +} diff --git a/R/transform-files.R b/R/transform-files.R index 737c9281b..f49e013e4 100644 --- a/R/transform-files.R +++ b/R/transform-files.R @@ -169,15 +169,34 @@ parse_transform_serialize_r <- function(text, transformers, warn_empty = TRUE) { } return("") } - transformed_pd <- apply_transformers(pd_nested, transformers) - flattened_pd <- post_visit(transformed_pd, list(extract_terminals)) %>% - enrich_terminals(transformers$use_raw_indention) %>% - apply_ref_indention() %>% - set_regex_indention( - pattern = transformers$reindention$regex_pattern, - target_indention = transformers$reindention$indention, - comments_only = transformers$reindention$comments_only - ) + + width <- getOption("width") + + newline_ids <- integer(0) + tf <- transformers + repeat{ + add_line_break_at_pos_id <- mk_add_line_break_at_pos_id(newline_ids) + tf$line_break <- c(lst(add_line_break_at_pos_id),transformers$line_break) + transformed_pd <- apply_transformers(pd_nested, tf) + + flattened_pd <- post_visit(transformed_pd, list(extract_terminals)) %>% + enrich_terminals(transformers$use_raw_indention) %>% + apply_ref_indention() %>% + set_regex_indention( + pattern = transformers$reindention$regex_pattern, + target_indention = transformers$reindention$indention, + comments_only = transformers$reindention$comments_only + ) + + overflowed <- flattened_pd$pos_id[flattened_pd$col2>width] + + if(length(overflowed)){ + newline_ids <- unique(c(newline_ids, min(overflowed))) + }else{ + break + } + } + serialized_transformed_text <- serialize_parse_data_flattened(flattened_pd, start_line = start_line)