2021年4月2日星期五

Tools for converting tab, and newline to literal? (for vscode snippet)

Converting the invisible to literals

The question

Are there any extensions or external tools which can do this
input (copy and paste):

int main()  {          return 0;  }  

output (can be copied):

int main()\n{\n\n\n\treturn 0;\n}  

Why I want this

In creating custom snippets, it would be super cool if we can just copy the real code with tabs and newlines and somehow paste it directly in the corresponding json. But in reality, we have the body part which is a list of lines which, for me, is confusing and requires more typing, for the quotes and commas.
This is what I want, which works (copy and paste to the body EZ)

// in cpp.json  {      "main function": {          "prefix": "int main",          "body": ["int main()\n{\n\n\n\treturn 0;\n}"]      },  }  

,not this

{      "main function": {          "prefix": "int main",          "body": ["int main()", "{\n\n\n", "\treturn 0;", "}"]      },  }  

or this.

{      "main function": {          "prefix": "int main",          "body": ["int main()", "{", "", "", "", "\treturn 0;", "}"]      },  }  

It would be so much faster and encouraging to just copy a code block with complex structure, convert it to a single line with tabs and newline as \t and \n, and paste it to the body as a single string.

My current workaround (kinda acceptable)

I use this tool, https://onlineunicodetools.com/convert-unicode-to-string-literal, to convert unicode literals to a unicode escape sequence one liner thing.
input

int main()  {          return 0;  }  

output

\u0069\u006e\u0074\u0020\u006d\u0061\u0069\u006e\u0028\u0029\u000a\u007b\u000a\u000a\u000a\u0020\u0020\u0020\u0020\u0072\u0065\u0074\u0075\u0072\u006e\u0020\u0030\u003b\u000a\u007d  

This works

// ...  "body": ["\u0069\u006e\u0074\u0020\u006d\u0061\u0069\u006e\u0028\u0029\u000a\u007b\u000a\u000a\u000a\u0020\u0020\u0020\u0020\u0072\u0065\u0074\u0075\u0072\u006e\u0020\u0030\u003b\u000a\u007d"]  // ...  

but it's a nightmare to place tabstops and placeholders. So it's not quite good.

Edit

I've just come up with this Python script

# ------------------------------------------------------------------------  # ! make text with tabs and newline characters to a unicode one liner  # ! here https://onlineunicodetools.com/convert-unicode-to-string-literal    import sys      def main():      if len(sys.argv) == 2:          print_one_liner(sys.argv[1])      elif len(sys.argv) == 1:          unicode_str = input("Enter unicode escape sequence: ")          # example, Enter: \u0068\u0065\u006c\u006c\u006f          print_one_liner(unicode_str)      else:          exit(1)      def print_one_liner(uni: str) -> None:      """process "str" of uni code escape characters       and print them in unicode literal with newline and tab as \n and \t      """        list_of_ascii_hex = uni.replace("\\u", " ").split()      string = "".join(          list(map(lambda hex_string: chr(int(hex_string, 16)), list_of_ascii_hex)))      processed_string = ""      for each in string:          if each == '\n':              processed_string += "\\n"              continue          if each == '\t':              processed_string += "\\t"              continue          processed_string += each      print(processed_string)      if __name__ == "__main__":      main()    

which, when combined with the web tool, produces the desired output.

int main()\n{\n\n\n    return 0;\n}  

Edit 2

Only this is enough lol

import sys  import os  if os.name == 'nt':      import msvcrt  else:      import termios      def main():      raw_code_file = "code.txt"      if not os.path.exists(raw_code_file):          open(raw_code_file, "w").close()        wait_key("Press any key to open file, paste code, save, then return here")      os.system("start " + raw_code_file)      wait_key("Press any key to continue")        processed_code_file = "one-line-code.txt"      with open(raw_code_file) as f:          processed_string = transform_one_line(f.read())          with open(processed_code_file, 'w') as p:              p.write(processed_string)          os.system("start " + processed_code_file)          print(processed_string)      def transform_one_line(string: str) -> str:      """ process text with newline and tab characters as \n and \t """        processed_string = ""      for each in string:          if each == '\n':              processed_string += "\\n"              continue          if each == '\t':              processed_string += "\\t"              continue          if each == '"':              processed_string += "'"              continue          processed_string += each      return processed_string      def wait_key(prompt=None, end='\n'):      """ Wait for a key press on the console and return it as str type. """        if prompt:          print(prompt, end=end)        result = None      if os.name == 'nt':          result = msvcrt.getch()      else:          fd = sys.stdin.fileno()            oldterm = termios.tcgetattr(fd)          newattr = termios.tcgetattr(fd)          newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO          termios.tcsetattr(fd, termios.TCSANOW, newattr)            try:              result = sys.stdin.read(1)          except IOError:              pass          finally:              termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)        return result if type(result) == str else result.decode('utf-8')      if __name__ == "__main__":      main()    

Edit 3

Eventually, here it is! https://github.com/arskiir/one-liner

https://stackoverflow.com/questions/66925472/tools-for-converting-tab-and-newline-to-literal-for-vscode-snippet April 03, 2021 at 05:30AM

没有评论:

发表评论