4.6.17. Modify selected text and save to file

Question:

I know that SEL_SAVETO will save the selected text to target file, but how to modify the selected text such as add one blank line and then save to target file?

Answer, option one:

I'd say the correct answer is to change the order of these operations:

  1. save the selected text via SEL_SAVETO;
  2. modify the saved file by some external tool.

For example, sfk (Swiss File Knife) supports a lot of ways to modify a file, and, moreover, it supports commands chaining (i.e. it's possible to apply one modification, then apply another one to the result and so on), plus now it does support UTF-8 and UCS-2 files. So I'd recommend to try to use sfk for any additional file modifications.

Here are a few examples of how to append/insert text lines by means of sfk:

Answer, option two:

It's possible to modify the original text by means of SCI_ commands, save the modified text and then undo the changes.

For example, we can append a string in the following way (this example works with the entire document rather than with the selected text):

set local str ~ strfromhex 0D 00 0A 00 "Some string" // first 4 bytes are \r\n
set local str_len ~ strlensci $(str)
sci_sendmsg SCI_APPENDTEXT $(str_len) "$(str)" // append a string to the end of document
text_saveto $(SYS.TEMP)\out.txt // save to the output file
sci_sendmsg SCI_UNDO // undo

Here is an example that appends a string to the existing selection, saves it to a file and then reverts the text (and selection) to the previous state:

// getting the current selection
sci_sendmsg SCI_GETCURRENTPOS
set local pos = $(MSG_RESULT)
sci_sendmsg SCI_GETANCHOR
set local anchor = $(MSG_RESULT)

if $(pos) < $(anchor) then
  set local pos1 = $(pos)
  set local pos2 = $(anchor)
else
  set local pos1 = $(anchor)
  set local pos2 = $(pos)
endif

// appending a string to the selection 
set local str ~ strfromhex 0D 00 0A 00 "Some string" // first 4 bytes are \r\n
set local str_len ~ strlensci $(str)
sci_sendmsg SCI_INSERTTEXT $(pos2) "$(str)" // append a string to the end of selection
set local pos2 ~ $(pos2) + $(str_len)
sci_sendmsg SCI_SETSEL $(pos1) $(pos2) // update the selection
sel_saveto $(SYS.TEMP)\out.txt // save to the output file
sci_sendmsg SCI_UNDO // undo

// restoring the original selection
sci_sendmsg SCI_SETSEL $(anchor) $(pos)
 

See also: Applying external tool to selected text [4.6.1]; Processing & replacing the selection [4.6.3].