To join lines in a Vim file such that each line is 115 characters long and split by commas, you need a combination of text wrapping and line joining. Here's a step-by-step solution:
Step 1: Join all lines into a single line
If your file has lines split by commas (e.g., a,b,c on separate lines), first join them into a single line:
:%j
This merges all lines into one continuous string (e.g., a,b,c,d,e,...).
Step 2: Split the single line into 115-character lines, preferring commas
Now, split the long line into chunks of 115 characters, splitting at commas if possible. This requires a custom Vimscript function:
function! SplitLinesAtCommas()
let l:line = getline(1)
let l:chunk_size = 115
let l:result = []
let l:pos = 0
while l:pos < len(l:line)
let l:end = min([l:pos + l:chunk_size, len(l:line)])
let l:chunk = substr(l:line, l:pos, l:end - l:pos)
" Find the last comma within the chunk
let l:comma_pos = match(l:chunk, ',', -1)
if l:comma_pos != -1
let l:end = l:pos + l:comma_pos + 1
endif
" Add the chunk to the result
call add(l:result, substr(l:line, l:pos, l:end - l:pos))
let l:pos = l:end
endwhile
" Replace the original line with the new chunks
call setline(1, l:result)
normal! G
endfunction
" Run the function
call SplitLinesAtCommas()
Explanation
:%j: Joins all lines into a single line (use this only if your file has lines split by commas).
- Custom function:
- Splits the single line into 115-character chunks.
- Prioritizes splitting at commas to preserve data integrity.
- Replaces the original line with the split chunks.
Alternative (Simpler but Less Precise)
If you want to force 115-character lines without respecting commas:
:set textwidth=115
:set formatoptions=tc
:%norm gqq
textwidth=115: Ensures lines don’t exceed 115 characters.
formatoptions=tc: Enables auto-wrapping at text boundaries (including commas).
:norm gqq: Applies formatting to the entire file.
When to Use Which
- Use the custom function if commas are critical (e.g., CSV files).
- Use the simple
textwidth method for general text formatting.