import sublime
import sublime_plugin

import logging

from . import simple_markdown as markdown
from .simple_markdown import table

log = logging.getLogger(__name__)

    def run(self, edit):
class MarkdownTableFormatCommand(sublime_plugin.TextCommand):
        logging.basicConfig(level=logging.DEBUG)
        settings = \
            sublime.load_settings("MarkdownTableFormatter.sublime-settings")
        verbose = settings.get("verbose")
        margin = settings.get("margin")
        padding = settings.get("padding")
        justify = settings.get("default_justification")
        justify = markdown.table.Justify.from_string[justify]
        autoformat_on_save = settings.get("autoformate_on_save")

        if verbose:
            log.setLevel(logging.DEBUG)
        else:
            log.setLevel(logging.INFO)

        for region in self.view.sel():
            text = self.view.substr(region)
            # get all tables positions as (start,end) list
            positions = markdown.table.find_all(text)
            offset = 0
            for start, end in positions:
                raw_table = text[start:end]
                log.debug("table found:\n" + raw_table)
                table = markdown.table.format(raw_table, margin, padding,
                                              justify)
                log.debug("formatted output:\n" + table)

                # replace the raw table with the formetted one
                table_region = sublime.Region(region.begin() + start + offset,
                                              region.begin() + end + offset)
                self.view.replace(edit, table_region, table)

                # as table length will likely change, an offset is required to
                # keep the modified region consistent
                offset = offset + len(table) - (end - start)

@@ -164,32 +164,8 @@
 _)%0A%0A
-    def run(self, edit):
 %0Acla
@@ -223,16 +223,59 @@
 mmand):%0A
+    def run(self, edit, format_all=False):%0A
         
@@ -846,38 +846,358 @@
     
+ #
  for
- region in self.view.sel()
+mat selected regions or all file with no selection%0A        has_selection = len(self.view.sel()) and self.view.sel()%5B0%5D.size()%0A        if not format_all and has_selection:%0A            regions = self.view.sel()%0A        else:%0A            regions = %5Bsublime.Region(0, self.view.size())%5D%0A%0A        table_new_regions = %5B%5D%0A        for region in regions
 :%0A  
@@ -1431,19 +1431,20 @@
         
-raw
+prev
 _table =
@@ -1505,19 +1505,20 @@
 d:%5Cn%22 + 
-raw
+prev
 _table)%0A
@@ -1529,24 +1529,28 @@
             
+new_
 table = mark
@@ -1567,19 +1567,20 @@
 .format(
-raw
+prev
 _table, 
@@ -1596,16 +1596,20 @@
 adding,%0A
+    
         
@@ -1705,16 +1705,20 @@
 t:%5Cn%22 + 
+new_
 table)%0A%0A
@@ -1739,52 +1739,199 @@
   # 
-replace the raw table with the formetted one
+absolute original table position after some insertion/removal%0A                table_prev_begin = region.begin() + start + offset%0A                table_prev_end = region.begin() + end + offset
 %0A   
@@ -1945,24 +1945,29 @@
       table_
+prev_
 region = sub
@@ -1967,101 +1967,247 @@
 n = 
-sublime.Region(region.begin() + start + offset,%0A                                             
+%5C%0A                    sublime.Region(table_prev_begin, table_prev_end)%0A                %0A                # future table position after some insertion/removal%0A                table_new_begin = table_prev_begin%0A                table_new_end =
  reg
@@ -2212,35 +2212,37 @@
 egion.begin() + 
-end
+start
  + offset)%0A     
@@ -2234,18 +2234,139 @@
 + offset
+ + len(new_table
 )%0A
+                table_new_region = %5C%0A                    sublime.Region(table_new_begin, table_new_end)%0A%0A
         
@@ -2407,16 +2407,21 @@
 ble_
+prev_
 region, 
 tabl
@@ -2416,22 +2416,141 @@
 region, 
+new_
 table)
+%0A                # stack new regions to update selection%0A                table_new_regions.append(table_new_region)
 %0A%0A      
@@ -2599,146 +2599,778 @@
 ange
-,
  a
-n offset is required to%0A                # keep the modified region consistent%0A                offset = offset + len(table) - (end - start
+fter being formatted an%0A                # offset is required to keep positions consistent%0A                offset = offset + len(new_table) - len(prev_table)%0A%0A        if table_new_regions and not format_all:%0A            had_multiple_regions = has_selection and len(self.view.sel()) %3E 1%0A            self.view.sel().clear()%0A%0A            # I don't like having to hit 'esc' to get only one cursor back after%0A            # having formatted more than one table using one selection%0A            if had_multiple_regions or len(table_new_regions) == 1:%0A                log.debug(%22MULTIPLE REGION%22)%0A                self.view.sel().add_all(table_new_regions)%0A            else:%0A                cursor = sublime.Region(table_new_regions%5B0%5D.a)%0A                self.view.sel().add(cursor
 )%0A

Refactor and update selection after formatting