Format code

Posted on
  • How can I format code in Espruino IDE? Any hotkey? I can't find anythyng...

  • I don't believe there is anything built in. Save to a file and then format in another editor?

  • Yes, I just use online formatter. But I think IDE without code formatting...

  • You're right - there's no code formatter in the IDE. One could be added relatively easily if anyone felt like it though.

  • Code formatting will be really awesome to have.

  • Hi together, I'd like to bring attention to this topic again. I think it would be really great to have a code formatter available. Not only does it unify our code base e.g. in BangleApps, it can also prevent bugs (for instance, the typical if without braces problems, see https://softwareengineering.stackexchang­e.com/a/16530). I'm also willing to help implementing this (however, I'm not familiar with the code of EspruineWebIDE yet, so I'd need some help where to get started).

  • Sat 2021.05.29

    'I'm not familiar with the code of EspruineWebIDE yet'

    The repository:

    https://github.com/espruino/EspruinoWebI­DE


    Here is an online open source solution:

    https://beautifier.io/
    https://github.com/beautify-web/js-beaut­ify

  • Thanks. I've seen the the Github repo for EspruinoWebIDE. Anyway, it will take some time to understand how everything works... Maybe already some simple questions: Should this be implemented as a plugin? How can the formatter be registered to a certain key combination?

    And, regarding the beautifier link, why not use prettier?

    https://prettier.io/
    https://prettier.io/docs/en/browser.html­

    It is also open source and supported in almost any IDE - so it would provide consistent results also between different tools...

  • @neshanjo
    A simple example how to add a formatter.
    I used beautifier, because its so easy to add.
    And it does not need an internet connection.
    Steps:

    • add a file to js/plugins with following code
    • add a script tag in main.html to the new plugin
    • add beautify folder in js/libs
    • add beautify-file from github into this new folder
    • add script tag in main.html to beautify-file

      "use strict";
      (function(){
      var iconFolder;
      function init() {
        showIcon();
      }
      function showIcon(){
        iconFolder = Espruino.Core.App.addIcon({
          id: 'formatCode',icon: 'snippets',title: 'Prettyfie',order: 510,
          area: { name: "code",position: "top"},
          click: prettyfie
       });
      }
      function prettyfie(){
         var code = Espruino.Core.EditorJavaScript.getCode()­;
         code = js_beautify(code);
         Espruino.Core.EditorJavaScript.setCode(c­ode);
      }
      Espruino.Plugins.FormatCode = {
        init : init,  
      };
      }());
      
      

      ```

  • Nice @JumJum !

    what about a pull request for this cool feature?

  • @MaBe
    thanks but it would need some more work.
    For example:

    • add settings page
    • add options based on settings
    • is there a better tool, prettier for example ?
    • find a better icon
      My intention was to give a starting point ;-)
  • I think adding a single button/icon initially good to have, so that people can start using it. adding more features and polishing can be done as incremental release.

  • @JumJum Sorry for the delay and thanks very much for your code. This is exactly the kind of starting point I needed.

    Prettier doesn't need an internet connection, either. Here is what I did based on your initial example using prettier: https://github.com/neshanjo/EspruinoWebI­DE/tree/code-formatting-prettier
    Anybody here interested in this, can just checkout my fork and run npm install followed by npm start.

    My code also respects the indentation settings (tab width and tabs versus spaces).

    Indeed, there is still some work to do:

    1. Save the current cursor position
    2. Hide the icon in Blockly mode
    3. Add a keyboard shortcut
    4. Maybe another icon.

    I don't think, we need a settings page, though. I even think we should not have one in order to follow one code style. That's the idea behind prettier.

    I also made another branch using js-beautify: https://github.com/neshanjo/EspruinoWebI­DE/tree/code-formatting-js-beautify

    IMO, the main (only?) advantage of js-beautify over prettier is the smaller size. Prettier is more or less THE standard in modern JS development and available in many code editors and even from the command line. This is a nice feature, especially for BangleJS where every app uses its own code formatting style. Furthermore, it is actively developed by a large team, while js-beautify claims on their Github page that they are in need of more contributors.

    Just my 2ct. I'd be very happy to have any kind of code formatting soon.

    My next steps are to work on point 1 (see list above) and submit a MR. 2+3 should be done very easily by someone more familiar with the project.

  •   function formatCode() {
        var code = Espruino.Core.EditorJavaScript.getCode()­;
        var cursor = Espruino.Core.EditorJavaScript.getCodeMi­rror().getCursor();
        code = prettier.format(code, {
          parser: "babel",
          plugins: prettierPlugins,
          tabWidth: parseInt(Espruino.Config.TAB_SIZE),
          useTabs: Espruino.Config.INDENTATION_TYPE == "tabs",
          semi: true,
          singleQuote: true
        });
        Espruino.Core.EditorJavaScript.setCode(c­ode);
        Espruino.Core.EditorJavaScript.getCodeMi­rror().setCursor(cursor);
      }
    

    get/setCursor principally seems to do the trick, however, it changes the scrolling position. The line with the cursor becomes the last line in the editor window. You can try this by e.g. using large app code like https://github.com/espruino/BangleApps/b­lob/master/apps/trex/trex.js
    Any ideas how to fix this?

  • @neshanjo great to see what you did. Your point of adding setCursor, great idea.
    Looking forward to see a pull request for github ;-)

    Thanks for your nice feedback. Applause is what keeps artists going ;-)

    Beautifier was the first I used and it worked.
    At the end, using prettier or beautify does'nt matter (to me).
    BTW, could it be an option/help/possible to use prettier for selected code only ?

  • @neshanjo

    BTW, could it be an option/help/possible to use prettier for selected code only ?

    from @JumJum is very useful. Because often I use human formatting rather that machine formatting for the code to have a better visualize for repetitive source lines (such as lines 13 thru 27 in first code block in post http://forum.espruino.com/comments/13218­059/ - part of the conversation about Modular and extensible UI framework and ui elements.).

    To go a step further, I'd suggest to add a directive (as JS comment) that turns it off and on again, so the manual selection and formatting falls away. No matter what on formatting the whole file, the section(s) marked stay(s) untouched where as all other areas are formatted.

  • https://prettier.io/docs/en/ignore.html#­javascript

    You can ignore certain lines/parts of the code with this special comment.

    Implemeting "format only the selected code" is possible by using the Editor properties. This could be the next feature in another PR.

  • Just checked an idea for "format only the selected code" in my environment.
    At the end it is extremly easy to implement.
    Should be similiar for prettier

    	var code = Espruino.Core.EditorJavaScript.getCode()­;
    	var selected = Espruino.Core.EditorJavaScript.getSelect­edCode();
    	if(selected) code = code.replace(selected,js_beautify(select­ed,options) + "\n"); //had to add linefeed for beautify, don't know wether prettier  needs this
    	else code = js_beautify(code,options);
    	Espruino.Core.EditorJavaScript.setCode(c­ode);
    
    
  • @JumJum code.replace(selected, ... is dangerous since it may also override other places that, by accident, contain the same code as the selection. There are better ways by using start and end of the selection and replacing only this part - but, again, let us leave this to another PR (that we'd be happy to receive from you!).

    Edit: Have a look at https://codemirror.net/doc/manual.html#a­pi and try using Espruino.Core.EditorJavaScript.getCodeMi­rror().replaceSelection(...). This should do the trick.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Format code

Posted by Avatar for coopjmz @coopjmz

Actions