import sublime
import sublime_plugin
import re


class DecideTitle(sublime_plugin.EventListener):

    def on_modified_async(self, view):
        syntax = view.settings().get('syntax')
        if syntax and 'Markdown' in syntax:
            text = view.substr(sublime.Region(0, view.size()))
            it = re.finditer(r'^(#{1,6}(?!#))|^(-{3,}|={3,})', text, re.M)
            title = ''
            for m in it:
                if re.match(r'^(-{3,}|={3,})$', m.group()):
                    title_end = m.start() - 1
                    title_begin = text.rfind('\n', 0, title_end) + 1
                    title = text[title_begin: title_end]
                else:
                    title_begin = m.end()
                    title_end = re.search('(' + m.group() + ')?(\n|$)', text[title_begin:]).start() + title_begin
                    title = text[title_begin: title_end]
                break
            if len(title) == 0:
                firstLineEnd = text.find('\n')
                if firstLineEnd == -1:
                    firstLineEnd = len(text)
                title = text[0: firstLineEnd]

            title = title.strip()
            if view.file_name() is None and len(title) > 0:
                view.set_name(title[:55])

@@ -408,16 +408,111 @@
  in it:%0A
+                if '.front-matter' in view.scope_name(m.start()):%0A                    continue%0A
         
@@ -682,65 +682,8 @@
 + 1%0A
-                    title = text%5Btitle_begin: title_end%5D%0A
     
@@ -885,140 +885,125 @@
 itle
- = text%5Btitle_begin: title_end%5D%0A                break%0A            if len(title) == 0:%0A                firstLineEnd = text.find('%5Cn
+_begin = m.start() + 1%0A                if 'markup.raw.block.markdown' not in view.scope_name(title_begin).split(' 
 ')
+:
 %0A   
@@ -1019,75 +1019,49 @@
     
-if firstLineEnd == -1:%0A                    firstLineEnd = len(text)
+    break%0A            if len(title) == 0:
 %0A   
@@ -1090,21 +1090,28 @@
 ext%5B
-0: firstLineE
+title_begin: title_e
 nd%5D%0A

fix front matter caused title finding bug