Skip to content

Commit

Permalink
Merge pull request mtxr#173 from mtxr/feature/improve-expand-to
Browse files Browse the repository at this point in the history
Add more options for expanding the empty selection, improve output
  • Loading branch information
tkopets authored Jan 11, 2018
2 parents 0d26c82 + c455c1d commit 2621cbf
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 43 deletions.
143 changes: 104 additions & 39 deletions SQLTools.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,21 @@ def loadDefaultConnection():


def createOutput(panel=None, syntax=None, prependText=None):
onInitialOutput = None
if not panel:
panel = getOutputPlace(syntax)
panel, onInitialOutput = getOutputPlace(syntax)
if prependText:
panel.run_command('append', {'characters': str(prependText)})

initial = True

def append(outputContent):
# hide previously set command running message (if any)
Window().status_message('')
nonlocal initial
if initial:
initial = False
if onInitialOutput:
onInitialOutput()

# append content
panel.set_read_only(False)
panel.run_command('append', {'characters': outputContent})
Expand Down Expand Up @@ -165,58 +172,114 @@ def insertContent(content):


def getOutputPlace(syntax=None, name="SQLTools Result"):
if not settings.get('show_result_on_window', True):
showResultOnWindow = settings.get('show_result_on_window', False)
if not showResultOnWindow:
resultContainer = Window().find_output_panel(name)
if resultContainer is None:
resultContainer = Window().create_output_panel(name)
Window().run_command("show_panel", {"panel": "output." + name})
else:
resultContainer = None
views = Window().views()
for view in views:
if view.name() == name:
resultContainer = view
Window().focus_view(resultContainer)
break
if not resultContainer:
resultContainer = Window().new_file()
resultContainer.set_name(name)

resultContainer.set_scratch(True) # avoids prompting to save
resultContainer.set_read_only(True)
resultContainer.settings().set("word_wrap", "false")
resultContainer.set_read_only(False)
# set custom syntax highlight, only if one was passed explicitly,
# otherwise use Plain Text syntax
if syntax:
# if custom and SQL related, use that, otherwise defaults to SQL
if 'sql' in syntax.lower():
resultContainer.set_syntax_file(syntax)

def onInitialOutputCallback():
if settings.get('clear_output', False):
resultContainer.set_read_only(False)
resultContainer.run_command('select_all')
resultContainer.run_command('left_delete')
resultContainer.set_read_only(True)

# set custom syntax highlight, only if one was passed explicitly,
# otherwise use Plain Text syntax
if syntax:
# if custom and SQL related, use that, otherwise defaults to SQL
if 'sql' in syntax.lower():
resultContainer.set_syntax_file(syntax)
else:
resultContainer.set_syntax_file(SYNTAX_SQL)
else:
resultContainer.set_syntax_file(SYNTAX_SQL)
else:
resultContainer.set_syntax_file(SYNTAX_PLAIN_TEXT)
resultContainer.set_syntax_file(SYNTAX_PLAIN_TEXT)

# hide previously set command running message (if any)
Window().status_message('')

if settings.get('clear_output', False):
resultContainer.run_command('select_all')
resultContainer.run_command('left_delete')
if not showResultOnWindow:
# if case this is an output pannel, show it
Window().run_command("show_panel", {"panel": "output." + name})

return resultContainer
Window().focus_view(resultContainer)

return resultContainer, onInitialOutputCallback

def getSelection():

def getSelectionText():
text = []
if View().sel():
for region in View().sel():
if region.empty():
if not settings.get('expand_to_paragraph', False):
text.append(View().substr(View().line(region)))
else:
text.append(View().substr(expand_to_paragraph(View(), region.b)))
else:
text.append(View().substr(region))

selectionRegions = getSelectionRegions()

if not selectionRegions:
return text

for region in selectionRegions:
text.append(View().substr(region))

return text


def getSelectionRegions():
expandedRegions = []

if not View().sel():
return None

# If we would need to expand the empty selection, then which type:
# 'file', 'view' = use text of current view
# 'paragraph' = paragraph(s) (text between newlines)
# 'line' = current line(s)
expandTo = settings.get('expand_to', 'file')
if not expandTo:
expandTo = 'file'

# keep compatibility with previous settings
expandToParagraph = settings.get('expand_to_paragraph')
if expandToParagraph is True:
expandTo = 'paragraph'

expandTo = str(expandTo).strip()
if expandTo not in ['file', 'view', 'paragraph', 'line']:
expandTo = 'file'

for region in View().sel():
# if user did not select anything - expand selection,
# otherwise use the currently selected region
if region.empty():
if expandTo in ['file', 'view']:
region = sublime.Region(0, View().size())
# no point in further iterating over selections, just use entire file
return [region]
elif expandTo == 'paragraph':
region = expand_to_paragraph(View(), region.b)
else:
# expand to line
region = View().line(region)

# even if we could not expand, avoid adding empty regions
if not region.empty():
expandedRegions.append(region)

return expandedRegions


def getCurrentSyntax():
view = View()
currentSyntax = None
Expand Down Expand Up @@ -472,7 +535,7 @@ def cb(index):
functionName = ST.functions[index].split('(', 1)[0]
return ST.conn.getFunctionDescription(functionName, createOutput(syntax=currentSyntax))

# get everything until first occurence of "(", e.g. get "function_name"
# get everything until first occurrence of "(", e.g. get "function_name"
# from "function_name(int)"
ST.selectFunction(cb)

Expand All @@ -485,7 +548,7 @@ def run():
return

Window().status_message(MESSAGE_RUNNING_CMD)
ST.conn.explainPlan(getSelection(), createOutput())
ST.conn.explainPlan(getSelectionText(), createOutput())


class StExecute(WindowCommand):
Expand All @@ -496,7 +559,7 @@ def run():
return

Window().status_message(MESSAGE_RUNNING_CMD)
ST.conn.execute(getSelection(), createOutput())
ST.conn.execute(getSelectionText(), createOutput())


class StExecuteAll(WindowCommand):
Expand All @@ -514,10 +577,12 @@ def run():
class StFormat(TextCommand):
@staticmethod
def run(edit):
for region in View().sel():
# if selection region is empty, use whole file as region
if region.empty():
region = sublime.Region(0, View().size())
selectionRegions = getSelectionRegions()

if not selectionRegions:
return

for region in selectionRegions:
textToFormat = View().substr(region)
View().replace(edit, region, Utils.formatSql(textToFormat, settings.get('format', {})))

Expand Down Expand Up @@ -550,7 +615,7 @@ def cb(index):
class StSaveQuery(WindowCommand):
@staticmethod
def run():
query = getSelection()
query = getSelectionText()

def cb(alias):
queries.add(alias, query)
Expand Down Expand Up @@ -656,7 +721,7 @@ def plugin_loaded():
# this ensures we have empty settings file in 'User' directory during first start
# otherwise sublime will copy entire contents of 'SQLTools.sublime-settings'
# which is not desirable and prevents future changes to queries and other
# sensible defaults defined in settings file, as those would be overriden by content
# sensible defaults defined in settings file, as those would be overridden by content
# from older versions of SQLTools in 'User\SQLTools.sublime-settings'
sublimeUserFolder = getSublimeUserFolder()
userSettingFile = os.path.join(sublimeUserFolder, SQLTOOLS_SETTINGS_FILE)
Expand Down
10 changes: 7 additions & 3 deletions SQLTools.sublime-settings
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,17 @@
"sqsh" : "sqsh"
},

// use paragraph (text between newlines), if selection is empty
"expand_to_paragraph" : false,
// If there is no SQL selected, use "expanded" region.
// Possible options:
// "file" - entire file contents
// "paragraph" - text between newlines relative to cursor(s)
// "line" - current line of cursor(s)
"expand_to": "file",

// puts results either in output panel or new window
"show_result_on_window" : false,

// clears the output of prev. query
// clears the output of previous query
"clear_output" : true,

// query timeout in seconds
Expand Down
2 changes: 1 addition & 1 deletion SQLToolsAPI/Connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def execute(self, queries, callback, stream=None):
args = self.buildArgs(queryName)
env = self.buildEnv()

Log("Query: " + queryToRun)
Log("Query: " + str(queryToRun))

self.Command.createAndRun(args=args,
env=env,
Expand Down

0 comments on commit 2621cbf

Please sign in to comment.