Retaining a text file's existing ANSI or Unicode format after editing

Get help with using AutoHotkey and its commands and hotkeys
Lem2001
Posts: 63
Joined: 27 Jun 2017, 17:59

Retaining a text file's existing ANSI or Unicode format after editing

27 Oct 2019, 15:37

 
I'm using some Regex to perform text edits on the contents of a plain text ini file.

Code: Select all

FileDelete, TestINI_New.ini
FileRead, AllFile, TestINI.ini
FileAppend, % RegExReplace(AllFile, "`amsU)(?<=\[Recent\])(.*)(?=^\[\w+]$)","`n`n`n$2"), TestINI_New.ini
run, TestINI_New.ini
However, when these changes are saved, it is altering the format of my Unicode BOM ini files and turning them into ANSI.

I have found a thread where it was suggested that adding , UTF-8 to the and of a FileAppend would save as Unicode. However, I don't want to force all ini files (even if they were in ANSI to begin with) to be saved as Unicode. I only want the files that are already Unicode to be saved as Unicode.

How can adapt the above code example so that the existing format of the ini file is retained (regardless of whether it's ANSI or UNICODE BOM) after the FileAppend command has altered it and saved the changes?
User avatar
jeeswg
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Retaining a text file's existing ANSI or Unicode format after editing

27 Oct 2019, 16:34

- For FileAppend, for the encoding, you'd want CP0 (for ANSI) or UTF-16. (Not UTF-8.)
- The AHK IniXXX commands, and the relevant Winapi functions, don't handle UTF-8 natively, although there are workarounds:
UTF-8 ini files - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=38511

- To get the encoding, here's some example code:
file set text/empty/get encoding/force read with specific encoding - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=47084

Code: Select all

;e.g. vEnc := JEE_FileGetEncoding(vPath)
;output examples: CP1252, UTF-8, UTF-16
JEE_FileGetEncoding(vPath)
{
	if !(oFile := FileOpen(vPath, "r"))
		return
	vEnc := oFile.Encoding
	oFile.Close()
	return vEnc
}
Cheers.
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA

Return to “Ask For Help”

Who is online

Users browsing this forum: A_AhkUser, Bing [Bot], boiler, enrica, keedooh and 43 guests