...

Source file src/github.com/noirbizarre/gonja/tokens/position.go

Documentation: github.com/noirbizarre/gonja/tokens

     1  package tokens
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  type Pos interface {
     9  	Pos() int
    10  }
    11  
    12  // Position describes an arbitrary source position
    13  // including the file, line, and column location.
    14  // A Position is valid if the line number is > 0.
    15  //
    16  type Position struct {
    17  	Filename string // filename, if any
    18  	Offset   int    // offset, starting at 0
    19  	Line     int    // line number, starting at 1
    20  	Column   int    // column number, starting at 1 (byte count)
    21  }
    22  
    23  // IsValid reports whether the position is valid.
    24  func (pos *Position) IsValid() bool { return pos.Line > 0 }
    25  
    26  // Pos return the current offset starting at 0
    27  func (pos *Position) Pos() int { return pos.Offset }
    28  
    29  // String returns a string in one of several forms:
    30  //
    31  //	file:line:column    valid position with file name
    32  //	file:line           valid position with file name but no column (column == 0)
    33  //	line:column         valid position without file name
    34  //	line                valid position without file name and no column (column == 0)
    35  //	file                invalid position with file name
    36  //	-                   invalid position without file name
    37  //
    38  func (pos Position) String() string {
    39  	s := pos.Filename
    40  	if pos.IsValid() {
    41  		if s != "" {
    42  			s += ":"
    43  		}
    44  		s += fmt.Sprintf("%d", pos.Line)
    45  		if pos.Column != 0 {
    46  			s += fmt.Sprintf(":%d", pos.Column)
    47  		}
    48  	}
    49  	if s == "" {
    50  		s = "-"
    51  	}
    52  	return s
    53  }
    54  
    55  func ReadablePosition(pos int, input string) (int, int) {
    56  	before := input[:pos]
    57  	lines := strings.Split(before, "\n")
    58  	length := len(lines)
    59  	return length, len(lines[length-1]) + 1
    60  }
    61  

View as plain text