diff --git a/spec/app/syntax-spec.coffee b/spec/app/syntax-spec.coffee index b532decef..5cf79f7e3 100644 --- a/spec/app/syntax-spec.coffee +++ b/spec/app/syntax-spec.coffee @@ -12,10 +12,16 @@ describe "the `syntax` global", -> filePath = require.resolve("fixtures/shebang") expect(syntax.grammarForFilePath(filePath).name).toBe "Ruby" - it "only use the first line to determine the syntax", -> + it "uses the number of newlines in the first line regex to determine the number of lines to test against", -> fileContent = "first-line\n" expect(syntax.grammarForFilePath("dummy.coffee", fileContent).name).toBe "CoffeeScript" + fileContent = '' + expect(syntax.grammarForFilePath("grammar.tmLanguage", fileContent).name).toBe "Plain Text" + + fileContent += '\n' + expect(syntax.grammarForFilePath("grammar.tmLanguage", fileContent).name).toBe "Property List (XML)" + it "doesn't read the file when the file contents are specified", -> filePath = require.resolve("fixtures/shebang") filePathContents = fs.read(filePath) diff --git a/src/app/syntax.coffee b/src/app/syntax.coffee index ab61bf122..9c176fefe 100644 --- a/src/app/syntax.coffee +++ b/src/app/syntax.coffee @@ -39,13 +39,30 @@ class Syntax grammarByFirstLineRegex: (filePath, fileContents) -> try - fileContents = fs.read(filePath) unless fileContents? + fileContents ?= fs.read(filePath) catch e - null + return - if fileContents - firstLine = fileContents.match(/^.*$/m) - _.find @grammars, (grammar) -> grammar.firstLineRegex?.test(firstLine) + return unless fileContents + + lines = fileContents.split('\n') + _.find @grammars, (grammar) -> + regex = grammar.firstLineRegex + return unless regex? + + escaped = false + numberOfNewlinesInRegex = 0 + for character in regex.source + switch character + when '\\' + escaped = !escaped + when 'n' + numberOfNewlinesInRegex++ if escaped + escaped = false + else + escaped = false + + regex.test(lines[0..numberOfNewlinesInRegex].join('\n')) grammarForScopeName: (scopeName) -> @grammarsByScopeName[scopeName]