printer: aligned adjacent attributes, closes #3

This commit is contained in:
Fatih Arslan 2015-11-04 17:21:17 +03:00
parent 59fd9d5a00
commit 6f84551a04
6 changed files with 30 additions and 21 deletions

View File

@ -323,11 +323,19 @@ func (p *printer) objectType(o *ast.ObjectType) []byte {
func (p *printer) alignedItems(items []*ast.ObjectItem) []byte { func (p *printer) alignedItems(items []*ast.ObjectItem) []byte {
var buf bytes.Buffer var buf bytes.Buffer
var longestLine int // find the longest key and value length, needed for alignment
var longestKeyLen int // longest key length
var longestValLen int // longest value length
for _, item := range items { for _, item := range items {
lineLen := len(item.Keys[0].Token.Text) + len(p.output(item.Val)) key := len(item.Keys[0].Token.Text)
if lineLen > longestLine { val := len(p.output(item.Val))
longestLine = lineLen
if key > longestKeyLen {
longestKeyLen = key
}
if val > longestValLen {
longestValLen = val
} }
} }
@ -339,25 +347,26 @@ func (p *printer) alignedItems(items []*ast.ObjectItem) []byte {
} }
} }
curLen := 0
for i, k := range item.Keys { for i, k := range item.Keys {
keyLen := len(k.Token.Text)
buf.WriteString(k.Token.Text) buf.WriteString(k.Token.Text)
for i := 0; i < longestKeyLen-keyLen+1; i++ {
buf.WriteByte(blank) buf.WriteByte(blank)
}
// reach end of key // reach end of key
if i == len(item.Keys)-1 && len(item.Keys) == 1 { if i == len(item.Keys)-1 && len(item.Keys) == 1 {
buf.WriteString("=") buf.WriteString("=")
buf.WriteByte(blank) buf.WriteByte(blank)
} }
curLen = len(k.Token.Text) // two blanks and one assign
} }
val := p.output(item.Val) val := p.output(item.Val)
valLen := len(val)
buf.Write(val) buf.Write(val)
curLen += len(val)
if item.Val.Pos().Line == item.Keys[0].Pos().Line && item.LineComment != nil { if item.Val.Pos().Line == item.Keys[0].Pos().Line && item.LineComment != nil {
for i := 0; i < longestLine-curLen+1; i++ { for i := 0; i < longestValLen-valLen+1; i++ {
buf.WriteByte(blank) buf.WriteByte(blank)
} }

View File

@ -1,8 +1,8 @@
aligned = { aligned = {
# We have some aligned items below # We have some aligned items below
foo = "bar" # yoo1 foo = "fatih" # yoo1
default = "bar" # yoo2 default = "bar" # yoo2
bar = "bar" # yoo3 bar = "bar and foo" # yoo3
default = { default = {
bar = "example" bar = "example"

View File

@ -1,8 +1,8 @@
aligned { aligned {
# We have some aligned items below # We have some aligned items below
foo = "bar" # yoo1 foo = "fatih" # yoo1
default = "bar" # yoo2 default = "bar" # yoo2
bar = "bar" # yoo3 bar = "bar and foo" # yoo3
default = { default = {
bar = "example" bar = "example"
} }