Code Monkey home page Code Monkey logo

plugin-pug's Introduction

     Prettier           Pug     

Prettier Pug plugin

license: MIT NPM package downloads Code Style: Prettier Build Status

Intro

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

This plugin adds support for the Pug language to Prettier.


Getting started

Simply install prettier and @prettier/plugin-pug as your project’s devDependencies:

npm add --save-dev prettier @prettier/plugin-pug
# or
yarn add --dev prettier @prettier/plugin-pug
# or
pnpm add --save-dev prettier @prettier/plugin-pug

Usage

CLI

npx prettier --write "**/*.pug" --plugin="@prettier/plugin-pug"
# or
yarn prettier --write "**/*.pug" --plugin="@prettier/plugin-pug"
# or
pnpm prettier --write "**/*.pug" --plugin="@prettier/plugin-pug"

Configuration file (.prettierrc)

{
  "plugins": ["@prettier/plugin-pug"]
}

See Standard Prettier overrides and Pug specific options for more options.

API

await prettier.format('code', {
  parser: 'pug',
  plugins: ['@prettier/plugin-pug'],
});

Workaround / Known Issue

There are some code examples that are not formatted well with this plugin and can damage your code.
But there are workarounds for it. These generate even better pug code!

Example

Issue 114

If you have tags at the top/root that are indented, they will lose indentation due to a technical limitation of pug.
Please check these before committing after running this plugin for the first time and fix them manually.

Integration with editors

If you are using a text editor that supports Prettier integration (e.g. Atom), you can have all Prettier perks for your Pug code too!

Use VSCode extension to get support for VSCode.

In order to get @prettier/plugin-pug working in projects that do not have local npm dependencies, you can install this plugin globally:

npm install --global prettier @prettier/plugin-pug

In this case, you might need to check the settings of your editor’s Prettier extension to make sure that a globally installed Prettier is used when it is not found in project dependencies (i.e. package.json).

Nevertheless, it is recommended to rely on local copies of prettier and @prettier/plugin-pug as this reduces the chance of formatting conflicts between project collaborators. This may happen if different global versions of Prettier or its Pug plugin are used.

Installing @prettier/plugin-pug either locally or globally may require you to restart the editor if formatting does not work right away.

Implementation details

This plugin is written in TypeScript and its quality is maintained using Prettier and Vitest.

Contributing

If you’re interested in contributing to the development of Prettier for Pug, you can follow the CONTRIBUTING guide from Prettier, as it all applies to this repository too.

To run @prettier/plugin-pug locally:

  • Clone this repository.
  • Execute pnpm run preflight.

Credits

This project was inspired by https://github.com/gicentre/prettier-plugin-elm.
Many thanks also to @j-f1, @lipis and @azz for the help in transferring this repository to the prettier organization.

Thanks to @fisker for the constant help and support in terms of Prettier Core support.

Thanks to @Peilonrayz, who gave me the idea to rewrite the printer into a class and thus make the code a lot more maintainable.

Thanks to @lehni, @SkyaTura and @shadowgate15 for the massive contribution and the introduction of many new features into the project.

Thanks to @maoberlehner to acknowledge @prettier/plugin-pug as officially well TTD tested at Vue Amsterdam 2023.

plugin-pug's People

Contributors

backbone87 avatar bitencode avatar chrisjansky avatar cloudless67 avatar david2tm avatar dependabot[bot] avatar dradows avatar homerjam avatar jounqin avatar jwerre avatar kaangokdemir avatar lehni avatar magurotabetai avatar mondeja avatar oiyouyeahyou avatar permanently avatar qnp avatar renovate-bot avatar renovate[bot] avatar ryeballar avatar seletskiy avatar shadowgate15 avatar shinigami92 avatar skyatura avatar yuheiy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

plugin-pug's Issues

Bug: Spaces get removed around interpolated tags

Steps to recreate:

Have a pug file like

div Some text with some #[strong Inline text] with text following it.

Run yarn prettier on it. The output is as follows, note the missing spaces around the [] brackets.

div Some text with some#[strong Inline text]with text following it.

This affects inline tags, like links, em, strong, i.e.

Some text with some Inline Text with text following it

vs

Some text with someInline Textwith text following it

Bug: Apostrophes are destroyed inside of angulars interpolation

Used configuration:

{
  "printWidth": 120,
  "tabWidth": 2,
  "useTabs": false,
  "singleQuote": false,
  "bracketSpacing": true
}

Input file:

.without-apostrophe(foo="{{'hello world' | uppercase}}")
  | {{'hello world' | uppercase}}

.with-apostrophe(foo="{{'it\'s me' | uppercase}}")
  | {{"it's me" | uppercase}}

Output file:

.without-apostrophe(foo="{{'hello world' | uppercase}}")
  | {{'hello world' | uppercase}}

.with-apostrophe(foo="{{'it's me' | uppercase}}")
  | {{ 'it"s me' | uppercase }}

Expected behavior:
It should not change a text which will be displayed (it's me was changed to it"s me).

Additional the handling of spaces after {{ and before }} should be consistently. The added spaces at the second {{ ... }} is the expected behavior.

wrong replacement of class

div(id = id, class = 'collapse' + (collapsed ? '' : ' show') + ' cardcontent') is transformed to .cardcontent(id=id, class="collapse' + (collapsed ? '' : ' show') + '")

easy to see that that will break behaviour

bug: Can not handle `<!DOCTYPE html>` correctly

<!DOCTYPE html>
html(lang="zh-Hans-CN")
  head
    meta(charset="UTF-8")
    meta(name="viewport", content="width=device-width, initial-scale=1.0")
    meta(http-equiv="X-UA-Compatible", content="ie=edge")
    link(rel="manifest", href="/manifest.json")
    title #{ htmlWebpackPlugin.options.title }
  body
    #root
Error: Unhandled token: {"type":"text-html","loc":{"start":{"line":1,"column":1},"end":{"line":1,"column":16}},"val":"<!DOCTYPE html>"}

Add support for the else-if

Can you add the support for the conditional else if ?
For example :

- var user = { description: 'foo bar baz' }
- var authorised = false
#user
  if user.description
    h2.green Description
    p.description= user.description
  else if authorised
    h2.blue Description
    p.description.
      User has no description,
      why not add one...
  else
    h2.red Description
    p.description User has no description

Bug: attribute starting with `:` formatted differently from the same attribute without `:`

Hey @Shinigami92, hope you're doing well.

Info

Tool Version
Plugin v1.2.0
Prettier v1.19.1
Node v13.12.0
OS linux

Input

span(
  :data=`{
    jobs: jobs.all,
    selected: jobs.selected,
    pipelines: [pipeline]
  }`
)

Output or Error

span(
  :data='{ jobs: jobs.all, selected: jobs.selected, pipelines: [pipeline] }'
)

Expected Output

span(
  :data=`{
    jobs: jobs.all,
    selected: jobs.selected,
    pipelines: [pipeline]
  }`
)

Additional Context

If :data is renamed to data (e.g. without :), then reformatting doesn't happen.

incorrect formatting inside data- attribute

option(data-content='<span class="' + cssIconClass(val) + '"></span><span class="text-' + cssColorCode(val) + '"> ' + val + '</span>') is formatted to option( data-content="<span class=\"' + cssIconClass(val) + '\"></span><span class=\"text-' + cssColorCode(val) + '\"> ' + val + '</span>" )

Support sorting of attributes

Support sorting of attributes

It would be nice if attributes could optionally be sorted.

Acceptance criterion

  • No breaking changes
  • Minor update
  • Sorting attributes is disabled by default
  • The order of attributes can be changed / customized
  • Tests are implemented

Any chance to get it work with vue single components?

Prettier works perfectly for the <script> tag of vue single-file compontens (.vue files), but it seems like this plugin doesn't work with vue's <template lang="pug">.

Do you know if it's possible to make it work?

Mixins and Includes

Hi there!
I am having an a weird issue with mixins and includes.
I am using the default settings.

The testing file:

doctype html

include ./includes/_helpers.pug

html
  head
    title Test
  body
    +stylesheet('test')

Issue 1

includes are turning into tags, like this:
include./includes/_helpers.pug

Issue 2

An error is returned for the +stylesheet() mixin.

[error] test.pug: Error: Unhandled token: {"type":"call","loc":{"start":{"line":9,"column":5},"end":{"line":9,"column":24}},"val":"stylesheet","args":"'test'"}
[error]     at Object.print (/Volumes/projects/production/node_modules/@prettier/plugin-pug/dist/index.js:461:35)
[error]     at callPluginPrintFunction (/Volumes/projects/production/node_modules/prettier/bin-prettier.js:13622:18)
[error]     at /Volumes/projects/production/node_modules/prettier/bin-prettier.js:13573:16
[error]     at Object.printComments (/Volumes/projects/production/node_modules/prettier/bin-prettier.js:13295:17)
[error]     at printGenerically (/Volumes/projects/production/node_modules/prettier/bin-prettier.js:13572:22)
[error]     at printAstToDoc (/Volumes/projects/production/node_modules/prettier/bin-prettier.js:13584:16)
[error]     at coreFormat (/Volumes/projects/production/node_modules/prettier/bin-prettier.js:13903:16)
[error]     at format (/Volumes/projects/production/node_modules/prettier/bin-prettier.js:14148:73)
[error]     at formatWithCursor (/Volumes/projects/production/node_modules/prettier/bin-prettier.js:14164:12)
[error]     at Object.formatWithCursor (/Volumes/projects/production/node_modules/prettier/bin-prettier.js:42758:15)

An interpolation following an id collapses into it.

The following valid pug code:

doctype html
html
  body
    h1#header #{title}

collapses into the following, which isn't valid pug:

doctype html
html
  body
    h1#header#{title}

This also happens with lone id's (#header #{title}) and unescaped interpolations (!{title}). It doesn't happen with classes (h1.header #{title}), though.

This seems to be a case of #27 that wasn't handled when the bug was closed.

Configurable quotes

Use prettier's singleQuote to correctly quote the attributes.
This should be overwritable via:

{
  "overrides": [
    {
      "files": "*.pug",
      "options": {
        "parser": "pug",
        "singleQuote": true
      }
    }
  ]
}

Wrong replacement of quotes

input(onClick="methodname(\"" + variable + "\", this)") is converted to input(onClick="methodname(\"\" + variable + \"\", this)")

this changes semantics massively

AngularJS (1) one-time-binding not supported

Info

Tool Version
Plugin v1.1.8
Prettier v1.19.1
Node v8.12.0
OS mac

Input

input(placeholder="{{:: 'some.token.to.translate' | translate}}")

Output or Error

["ERROR" - 2:02:53 PM] Error formatting document.
["ERROR" - 2:02:53 PM] Unhandled token: {"type":"attribute","loc":{"start":{"line":1,"column":7},"end":{"line":1,"column":65}},"name":"placeholder","val":"\"{{:: 'some.token.to.translate' | translate}}\"","mustEscape":true}
Error: Unhandled token: {"type":"attribute","loc":{"start":{"line":1,"column":7},"end":{"line":1,"column":65}},"name":"placeholder","val":"\"{{:: 'some.token.to.translate' | translate}}\"","mustEscape":true}
	at PugPrinter.build (redacted/node_modules/@prettier/plugin-pug/dist/printer.js:78:23)
	at Object.print (redacted/node_modules/@prettier/plugin-pug/dist/index.js:63:40)
	at callPluginPrintFunction (redacted/node_modules/prettier/index.js:12984:18)
	at redacted/node_modules/prettier/index.js:12935:16
	at Object.printComments (redacted/node_modules/prettier/index.js:12656:17)
	at printGenerically (redacted/node_modules/prettier/index.js:12934:22)
	at printAstToDoc (redacted/node_modules/prettier/index.js:12946:13)
	at coreFormat (redacted/node_modules/prettier/index.js:13265:13)
	at format (redacted/node_modules/prettier/index.js:13510:73)
	at formatWithCursor (redacted/node_modules/prettier/index.js:13526:12)
	at redacted/node_modules/prettier/index.js:44207:15
	at Object.format (redacted/node_modules/prettier/index.js:44226:12)
	at /Users/my.name/.vscode/extensions/esbenp.prettier-vscode-3.20.0/dist/extension.js:1:350954
	at t.default.safeExecution (/Users/my.name/.vscode/extensions/esbenp.prettier-vscode-3.20.0/dist/extension.js:1:351254)
	at t.default.<anonymous> (/Users/my.name/.vscode/extensions/esbenp.prettier-vscode-3.20.0/dist/extension.js:1:350934)
	at Generator.next (<anonymous>)
	at s (/Users/my.name/.vscode/extensions/esbenp.prettier-vscode-3.20.0/dist/extension.js:1:345019)

Expected Output

Additional Context

It looks like double colon (::) aka one-time binding isn't recognized if it is used inside quotes because p {{ :: 'some.token.to.translate' | translate }} doesn't error and formats the document.

Bug: class formatting introduces trailing parenthesis if class length is greater than prettier's printWidth setting

Info

Tool Version
Plugin v1.1.7
Prettier v1.19.1
Node v13.6.0
OS win,linux,mac

Input

  • With prettier's default setting of printWidth: 80
div(class="bg-red-10 border-l-2 border-red-600 text-red-700 mb-4 rounded-r-10 font-normal")

Output or Error

.bg-red-10.border-l-2.border-red-600.text-red-700.mb-4.rounded-r-10.font-normal(
)

Expected Output

.bg-red-10.border-l-2.border-red-600.text-red-700.mb-4.rounded-r-10.font-normal

Additional Context

Note the extra parens at the end of the actual output. These only appear if the input class length is > prettier's printWidth setting.

Add support for while and case

When I use case or while loop, I get an error in my code because your plugin doesn't support it.

You can reproduce the bug with the code of the pug documentation

- var n = 0;
ul
  while n < 4
    li= n++
- var friends = 1
case friends
  when 0: p you have no friends
  when 1: p you have a friend
  default: p you have #{friends} friends

Bug: Doesn't take the singleQuote option

Since the 1.0.10, singlequote are transformed into double quotes even if I set singleQuote option.
I tried with the 1.0.9 and I don't have this bug.

For example:

- const faker = require('faker')

is transformed into

- const faker = require("faker")

Bug: Error with assignments in vue attributes and prettier v2

Info

Tool Version
Plugin v1.1.10
Prettier v2.0.2
Node v13.10.1
OS mac

Input

v-text-field(
  v-model="password",
  :type="showPassword ? 'text' : 'password'",
  @click:append="(showPassword = !showPassword)"
)

Output or Error

Error: Unhandled token:
{
  "type": "attribute",
  "loc": {"start":{"line":31,"column":19},
  "end": {"line":31,"column":65}},
  "name": "@click:append",
  "val": "\"(showPassword = !showPassword)\"",
  "mustEscape": true
}

Expected Output

v-text-field(
  v-model="password",
  :type="showPassword ? 'text' : 'password'",
  @click:append="(showPassword = !showPassword)"
)

Additional Context

When using new prettier v2, vue attributes that contains assignments throw errors.

Support multilines javascript

I get an error when I use multiline javascript with pug.

Error: Unhandled token: {"type":"blockcode","loc":{"start":{"line":6,"column":3},"end":{"line":6,"column":4}}}
-
  const options = {
    fields: {},
    rules: {},
  }

Refer to pug documentation for prettier formatting

It would be nice if you refer more to pug formatting like they do in there documentation.
For example use space instead of comma to separate attributes.

If it's possible, add an parameter to make Class and ID Literal optional.

Incorrect splitting of attribute value when line is too long

Before formatting:

div
  table
    tbody
      tr
        td
          a(:href=`Nav.currentProject().repo(getRepository(pipeline).slug).buildNoContext()`)

After formatting:

div
  table
    tbody
      tr
        td
          a(
            :href='Nav.currentProject()
  .repo(getRepository(pipeline).slug)
  .buildNoContext()'
          )

This is incorrect syntax: no newlines accepted in single quotes.

Feature Request: Make the separation of attributes with a comma an option

Hi @Shinigami92 !
As we previously talked on #11 I am making a feature request!

Looking through Pug's docs, they never use comma to separate the attributes on tags.

I think we should keep it consistent and have that same behaviour as default.

I, personally would remove the comma separation completely but I can see how it can be nice for other users, so I propose we make it an option.

The option could be called useCommaAttributes, or something similar, it would be a boolean that if set to true would have the parser add commas to separate the attributes on tags.

Thanks again, and please let me know your thoughts.

Bug: doent respect printWidth of configuration (border values)

Info

Tool Version
Plugin v1.1.8
Prettier v1.19.1
Node v13.6.0
OS linux

Input

.baz
  .baz(foo="Lorem Ipsum is simply dummy text of the printing and typesetting industry.", bar="Lorem Ipsum is simply dum")

Long line is 122 characters long.

Output

.baz
  .baz(foo="Lorem Ipsum is simply dummy text of the printing and typesetting industry.", bar="Lorem Ipsum is simply dum")

Output is the same as input, which is wrong

Expected Output

.baz
  .baz(
    foo="Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
    bar="Lorem Ipsum is simply dum"
  )

Configuration

'use strict';
module.exports = {
  printWidth: 120,
  tabWidth: 2,
  useTabs: false,
  semi: true,
  singleQuote: false,
  trailingComma: 'es5',
  bracketSpacing: true,
  arrowParens: 'avoid',
};

printWidth is configured to 120, but if a line is 121 or 122 characters long, it doesn't add a new line but it should. If line is 123 characters long it is working as expected.

Transform wrapping html tags to pug

This

<!DOCTYPE html>
<html>

body
  p Indenting the body tag here would make no difference.
  <p>HTML itself isn't whitespace-sensitive.</p>
  ul
    li Item A
    li Item B
    li Item C
  <ul>
    <li>Item A</li>
    li Item B
    <li>Item C</li>
  </ul>

</html>

Should become this

doctype html
html

body
  p Indenting the body tag here would make no difference.
  p HTML itself isn't whitespace-sensitive.
  ul
    li Item A
    li Item B
    li Item C
  ul
    li Item A
    li Item B
    li Item C

Bug: class names not extracted correctly from class attribute

Info

Tool Version
Plugin v1.1.6
Prettier v1.19.1
Node v12.15.0
OS mac

Input

div(class="bg-red-100 border-l-4 border-red-600 text-red-700 p-4 mb-4")

Output or Error

.bg-red-100(.border-l-4.border-red-600.text-red-700.p-4.mb-4)

Expected Output

.bg-red-100.border-l-4.border-red-600.text-red-700.p-4.mb-4

Additional Context

As you can see, everything but the first class is wrapped inside parenthesis, which causes the class names not to be applied.

Bug: removes 2nd block with angular interpolation

Info

Tool Version
Plugin v1.1.9
Prettier v1.19.1
Node v13.6.0
OS linux

Input

foo(title="{{'something' | translate}} - {{'something else' | translate}}")

Output or Error

foo(title="{{ 'something' | translate }}")

Expected Output

foo(title="{{ 'something' | translate }} - {{ 'something else' | translate }}")

Moving to @prettier/plugin-pug

@prettier @lipis

Referring to prettier/prettier#6245 (comment) and https://twitter.com/PrettierCode/status/1144730688727523328

Generally, I would support it if we move the repository to @prettier/plugin-pug and prettier/plugin-pug

But I have some questions:

  • Maintainer of the repo
    It would be very nice if I can stay as the repo maintainer
  • WebHooks
    I have currently setup a WebHook linked to my private Discord Server to be notified about everything
    Can I have this also in the new repo?
  • Publishing in scope of @prettier to npm
    How can I publish a new version of the plugin in the scope of prettier?
  • Transferring current issues
    Would be nice if also closed issue could be transferred
  • Azure Pipelines
    How can I maintain the Azure build pipeline?
    Also I want to setup junit reporter in near future

wrong new line in attributes

When we use:
prettier: 1.19.1
@prettier/plugin-pug: 1.1.5

if PUG is something like:

.foo(*ngIf="myObjectAsync | async as myObject; else fallbackTemplate")

then we get such result:

.foo(*ngIf="myObjectAsync | async as myObject;
else fallbackTemplate")

It shouldnt add any line breaks here, or if it does then it should add "\" at the end of first line.

Plugin makes syntax invalid

Hello, today while setting up prettier + prettier-pug I encountered this problem:

The prettier-pug plugin, when ran on a pug file with the --write flag, will fix the code style and as a side-effect sometimes corrupt the syntax of the file, producing an invalid file which cannot be processed on subsequent runs.

As an example here this completely valid pug file:

tag(key='value') #{identifier}
tag
  | #{identifier}

The prettier-pug produces this output, which is invalid:

tag(key='value')#{identifier}
tag
#{identifier}

When using the pug package, it reports this error:

Error: /file.pug:1:17
  > 1| tag(key='value')#{identifier}
-----------------------^
    2| tag
    3| #{identifier}
    4| 
  
Unexpected token `interpolation` expected `text`, `interpolated-code`, `code`, `:`, `slash`, `newline` or `eos`

When running pug-prettier on the new pug file, it produces this error:

[error] /file.pug: Error: Unhandled token: {"type":"interpolation","loc":{"start":{"line":1,"column":17},"end":{"line":1,"column":30}},"val":"identifier"}
[error]     at _loop_1 (/node_modules/@prettier/plugin-pug/dist/index.js:542:35)
[error]     at Object.print (/node_modules/@prettier/plugin-pug/dist/index.js:546:21)
[error]     at callPluginPrintFunction (/node_modules/prettier/bin-prettier.js:13622:18)
[error]     at /node_modules/prettier/bin-prettier.js:13573:16
[error]     at Object.printComments (/node_modules/prettier/bin-prettier.js:13295:17)
[error]     at printGenerically (/node_modules/prettier/bin-prettier.js:13572:22)
[error]     at printAstToDoc (/node_modules/prettier/bin-prettier.js:13584:16)
[error]     at coreFormat (/node_modules/prettier/bin-prettier.js:13903:16)
[error]     at format (/node_modules/prettier/bin-prettier.js:14148:73)
[error]     at formatWithCursor (/node_modules/prettier/bin-prettier.js:14164:12)

Impossible to format pug with 'each'

I use the "Format Document" option with the VSCode extension on this simple pug file:

- const files = ['script.js']

each jsFile in files
  script(src=jsFile)

But I got this error.

Unhandled token/Users/loisboubault/Tools/test/test.pug:: {"type"/Users/loisboubault/Tools/test/test.pug::"each","loc"/Users/loisboubault/Tools/test/test.pug::{"start"/Users/loisboubault/Tools/test/test.pug::{"line"/Users/loisboubault/Tools/test/test.pug::3,"column"/Users/loisboubault/Tools/test/test.pug::1},"end"/Users/loisboubault/Tools/test/test.pug::{"line"/Users/loisboubault/Tools/test/test.pug::3,"column"/Users/loisboubault/Tools/test/test.pug::21}},"val"/Users/loisboubault/Tools/test/test.pug::"jsFile","key"/Users/loisboubault/Tools/test/test.pug::null,"code"/Users/loisboubault/Tools/test/test.pug::"files"}
Do prettier pug plugin supports "each" iterations ?

vue-prettier removes completely valid backslash escaping character if it is occuring in text node after some text

@prettier/plugin-pug version: 1.1.2

This is live recording of an editor which triggers prettier on each save.
As you can see there, every time I save a file one backslash is disappearing after another.

vue-prettier bug

I also want to mention, that:

  • will cause to \ to disappear on formatting:

    h2 ID \#{{ id }}
    
  • will not cause \ to disappear:

    h2 \#{{ id }}
    

So, the problem is somehow linked to the text which precedes \.

Escaping is described here: https://pugjs.org/language/interpolation.html#string-interpolation-escaped

Support wrap for attributes

Currently all attributes of a tag are written in the same line.
We should wrap the attributes at a certain point. This can be the maximum line length (prettier's printWidth) and / or a configurable number of attributes.
So if we configure "maxAttributesBeforeWrap": 4, attributes should be wrapped if there are more than 4.
The name of the option should be improved 😄, please suggest another one.

mixin arguments can not be formatted

If I have the following formatted code:

+link({
  name: 'Solutions', 
  subnav: {
    sublinks: [
       {name: 'WISP', url: '#', icon:'wisp'},
       {name: 'Fiber', url: '#', icon:'fiber'},
       {name: 'MDU', url: '#', icon:'mdu'},
       {name: 'Voice', url: '#', icon:'voice'},
       {name: 'Cable', url: '#', icon:'cable'},
       {name: 'Enterprise', url: '#', icon:'enterprise'}
    ]
  }
})

It gets formatted to the following:

+link({ name: 'Solutions', subnav: { sublinks: [ {name: 'WISP', url: '#', icon:'wisp'}, {name: 'Fiber', url: '#', icon:'fiber'}, {name: 'MDU', url: '#', icon:'mdu'}, {name: 'Voice', url: '#', icon:'voice'}, {name: 'Cable', url: '#', icon:'cable'}, {name: 'Enterprise', url: '#', icon:'enterprise'} ] }})

Is there any possible way to prevent this reformatting from happening, as it makes parsing the information far more difficult?

Bug: Extra spaces get removed

Info

Tool Version
Plugin v1.1.6
Prettier v1.19.1
Node v13.6.0
OS win,linux,mac

Input

|  xxx

Two spaces before xxx to get an extra space.

Expected Output

|
| xxx

Actual Output

| xxx

Just one space before xxx. No space will be displayed.

Don't replace != to =

I would like to pass Unescaped Buffered Code in my div but your plugin replace the != to = .

For example:
div!='<p>Hello</p>'

is transformed to

div= '<p>Hello</p>'

Comment blocks breaking tab index

When trying to comment out tab indexed pug code, prettier seems to be stripping out the tab index, rendering the code useless upon uncommenting.

I put together 2 quick example showing the issue I'm getting for both pug block comments, as well as individual line comments

Block Comment
block-comment

And similarly, if I comment out each line, I lose my tab index...

Line Comment
line-comment

I'm running prettier via VScode and have it format my file on-save. My .prettierrc file can be found below:

{
  "tabWidth": 2,
  "singleQuote": true,
  "jsxBracketSameLine": true,
  "jsxSingleQuote": true,
  "htmlWhitespaceSensitivity": "css",
  "overrides": [
    {
      "files": "*.pug",
      "options": {
        "singleQuote": true,
        "printWidth": 120,
        "attributeSeparator": "as-needed"
      }
    }
  ]
}

and my .pug-lintrc file, which even when empty still has this issue, is here:

{
  "disallowBlockExpansion": true,
  "disallowClassAttributeWithStaticValue": true,
  "disallowClassLiteralsBeforeAttributes": null,
  "disallowClassLiteralsBeforeIdLiterals": true,
  "disallowClassLiterals": null,
  "disallowDuplicateAttributes": true,
  "disallowHtmlText": null,
  "disallowIdAttributeWithStaticValue": true,
  "disallowIdLiteralsBeforeAttributes": null,
  "disallowLegacyMixinCall": true,
  "disallowMultipleLineBreaks": true,
  "disallowSpaceAfterCodeOperator": null,
  "disallowSpacesInsideAttributeBrackets": null,
  "disallowSpecificAttributes": null,
  "disallowSpecificTags": null,
  "disallowStringConcatenation": true,
  "disallowStringInterpolation": null,
  "disallowTagInterpolation": true,
  "disallowTemplateString": null,
  "maximumNumberOfLines": null,
  "requireClassLiteralsBeforeAttributes": true,
  "requireClassLiteralsBeforeIdLiterals": null,
  "requireIdLiteralsBeforeAttributes": true,
  "requireLineFeedAtFileEnd": true,
  "requireLowerCaseTags": true,
  "requireSpaceAfterCodeOperator": true,
  "requireSpacesInsideAttributeBrackets": null,
  "requireSpecificAttributes": [
    {
      "html": "lang"
    },
    {
      "form": "action"
    },
    {
      "img": "alt"
    },
    {
      "input": "type"
    },
    {
      "input[type=submit]": "value"
    }
  ],
  "requireStrictEqualityOperators": true,
  "validateAttributeQuoteMarks": "'",
  "validateDivTags": true,
  "validateExtensions": null,
  "validateIndentation": 2,
  "validateLineBreaks": "LF",
  "validateSelfClosingTags": true,
  "validateTemplateString": true
}

As far as I can tell, I'm not doing anything crazy so I'm not really sure what is going on. This also wasn't an issue for me prior to prettier removing the config from vscode settings. Let me know if there is anything further I could provide.

In the meantime, I have disabled prettier from handling commented out code within my pug file until this is resolved.

Formatting of multiple include directives

This may be ignorance or misconfiguration on my part, but I'm having trouble figuring it out.

Whenever I use two or more include statements consecutively, prettier removes all indentation after the first instance.

Eg. If I create a new project:

npm init -y
npm i -D pug prettier @prettier/plugin-pug

create an index.pug:

doctype 
html
    head
    body
        include in1
        include in2
        include in3

then run prettier: npx prettier index.pug

I get the output:

doctype
html
    head
    body
        include in1
include in2
include in3

What am I doing wrong? Thanks.

Parser Error: Missing expected } at the end of the expression

When we use:
prettier: 1.19.1
@prettier/plugin-pug: 1.1.5

if PUG is something like:

.foo([myAttribute]="{param:'hello {name}' | translate:{'name':arg}}")

then we get such Error:

foo.pug[error] foo.pug: SyntaxError: Missing expected } at the end of the expression [{{{param:'hello {name}' | translate:{'name':arg}}}}] in angular-estree-parser
[error] at o (/myProject/node_modules/prettier/parser-angular.js:15:16477)
[error] at t.parseNgInterpolation (/myProject/node_modules/prettier/parser-angular.js:15:17607)
[error] at n (/myProject/node_modules/prettier/parser-angular.js:15:28488)
[error] at Object.t.parseInterpolation (/myProject/node_modules/prettier/parser-angular.js:15:28826)
[error] at /myProject/node_modules/prettier/parser-angular.js:15:29569
[error] at Object.parse (/myProject/node_modules/prettier/parser-angular.js:15:29226)
[error] at Object.parse (/myProject/node_modules/prettier/index.js:9739:19)
[error] at coreFormat (/myProject/node_modules/prettier/index.js:13252:23)
[error] at format (/myProject/node_modules/prettier/index.js:13510:73)
[error] at formatWithCursor (/myProject/node_modules/prettier/index.js:13526:12)

Incorrect formatting ID attribute of anchor

version

example

  • Origin ( test.pug )
a(href="/index.html")#xxx.btn
a#xxx(href="/index.html").btn
  • Compiled (test.html)
$ ./node_modules/.bin/pug test.pug 
<a class="btn" href="/index.html" id="xxx"></a><a class="btn" id="xxx" href="/index.html"></a>
  • Formatted
$ ./node_modules/.bin/prettier "test.pug"  
a(href="/index#xxx.html").btn  # <- this is wierd
a#xxx(href="/index.html").btn

Bug: Unhandled token error if angular pipe has a parameter

Info

Tool Version
Plugin v1.1.6
Prettier v1.19.1
Node v13.6.0
OS linux

Input

div
  | {{'foo' | baz:bar}}

Output or Error

Error: Unhandled token: {"type":"text","loc":{"start":{"line":2,"column":5},"end":{"line":2,"column":24}},"val":"{{'foo' | baz:bar}}"}
[error]     at PugPrinter.build (/home/valeri/workspaceA4/notices/node_modules/@prettier/plugin-pug/dist/printer.js:77:23)
[error]     at Object.print (/home/valeri/workspaceA4/notices/node_modules/@prettier/plugin-pug/dist/index.js:63:40)
[error]     at callPluginPrintFunction (/home/valeri/workspaceA4/notices/node_modules/prettier/bin-prettier.js:12988:18)
[error]     at /home/valeri/workspaceA4/notices/node_modules/prettier/bin-prettier.js:12939:16
[error]     at Object.printComments (/home/valeri/workspaceA4/notices/node_modules/prettier/bin-prettier.js:12660:17)
[error]     at printGenerically (/home/valeri/workspaceA4/notices/node_modules/prettier/bin-prettier.js:12938:22)
[error]     at printAstToDoc (/home/valeri/workspaceA4/notices/node_modules/prettier/bin-prettier.js:12950:13)
[error]     at coreFormat (/home/valeri/workspaceA4/notices/node_modules/prettier/bin-prettier.js:13271:13)
[error]     at format (/home/valeri/workspaceA4/notices/node_modules/prettier/bin-prettier.js:13516:73)
[error]     at formatWithCursor (/home/valeri/workspaceA4/notices/node_modules/prettier/bin-prettier.js:13532:12)

Expected Output

div
  | {{'foo' | baz:bar}}

Additional Context

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.