Now I think I have a solution that conforms to the spirit of **Nim** :

  * When input is taken from the terminal, it is regarded to / should be 
**UTF-16 LE** encoded.
  * When input is taken from a file, it is regarded to / should be **UTF-8** 
encoded.
  * **echo** does not have to be overloaded; output is **UTF-8** encoded.



This means piping should work in any case.
    
    
    #console.nim
    
    when defined(windows):
      import system/widestrs
      import terminal
      
      proc setMode(fd: int, mode: int): int
           {.importc: "_setmode", header: "io.h".}
      
      proc fgetws(str: WideCString, numChars: int, stream: File): bool
           {.importc, header: "stdio.h".}
      
      proc consoleReadLine*(line: var string): bool =
        if stdin.isatty:
          discard stdin.getFileHandle.setMode(0x20000)  #_O_U16TEXT
          let buffer = newWideCString("", 256)
          result = fgetws(buffer, 256, stdin)
          let length = buffer.len
          if length > 0 and buffer[length - 1].int == 10:  #discard '\n'
            buffer[length - 1] = Utf16Char(0)
            let buffer2 = newWideCString("", 2)  #discard extra '\n'
            discard fgetws(buffer2, 2, stdin)
          line = $buffer
          discard stdin.getFileHandle.setMode(0x8000)   #_O_BINARY
        else:
          result = stdin.readLine(line)
      
      proc consoleReadLine*(): string =
        discard consoleReadLine(result)
    
    else:
      proc consoleReadLine*(line: var string): bool =
        result = stdin.readLine(line)
      
      proc consoleReadLine*(): string =
        result = stdin.readLine
    
    Run

Reply via email to