Skip to content

Commit

Permalink
Add insert_date_panel command
Browse files Browse the repository at this point in the history
Opens a panel with pre-defined settings and previews them
  • Loading branch information
FichteFoll committed Jan 11, 2014
1 parent 9279d6b commit 24a0cc5
Show file tree
Hide file tree
Showing 4 changed files with 154 additions and 20 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
InsertDate Changelog
====================

~current iteration~
-------------------

- Added a panel to choose a format from, configurable via settings


v0.5.0 (2014-01-11)
-------------------

Expand Down
23 changes: 19 additions & 4 deletions format_date.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
import pytz
from pytz.exceptions import UnknownTimeZoneError

# Not using sublime.version here because it's supposed to be used externally too
import sys
if sys.version_info[0] != 2:
ST2 = sys.version_info[0] == 2

if ST2:
basestring = str


Expand Down Expand Up @@ -88,8 +91,11 @@ def __init__(self, local_tz=None, default=None):
if not default is None:
self.set_default(default)

def set_default(self, default):
self.default.update(default)
def set_default(self, update):
# Update only the keys that are defined in self.default
for k, v in update.items():
if k in self.default:
self.default[k] = v

def parse(self, format=None, tz_in=None, tz_out=None):
# 'unix'
Expand All @@ -98,7 +104,16 @@ def parse(self, format=None, tz_in=None, tz_out=None):

# anything else
dt = self.date_gen(tz_in, tz_out)
return self.date_format(dt, format)
text = self.date_format(dt, format)

# Fix potential unicode/codepage issues
if ST2 and isinstance(text, str):
try:
text = text.decode(locale.getpreferredencoding())
except UnicodeDecodeError:
text = text.decode('utf-8')

return text

def check_tzparam(self, tz, name):
if isinstance(tz, basestring):
Expand Down
80 changes: 66 additions & 14 deletions insert_date.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import locale

import sublime
import sublime_plugin

Expand All @@ -20,6 +18,14 @@
s = None


def status(msg, e=None):
msg = "[InsertDate] "
sublime.status_message(msg)
if e is not None:
msg += "\n%s: %s" % (type(e).__name__, e)
print(msg)


# I wrote this for InactivePanes, but why not just use it here as well?
class Settings(object):
"""Provides various helping functions for wrapping the sublime settings objects.
Expand Down Expand Up @@ -135,7 +141,7 @@ def clear_callback(self, clear_auto_update=False):
return cb


# The actual command
# The actual commands
class InsertDateCommand(sublime_plugin.TextCommand):
"""Prints Date according to given format string
"""
Expand All @@ -155,28 +161,21 @@ def run(self, edit, format=None, prompt=False, tz_in=None, tz_out=None):
)
return # Call already handled

if format == '' or (isinstance(format, basestring) and format.isspace()):
# Emtpy string or only whitespaces entered in input panel
if format == '' or not isinstance(format, basestring) or format.isspace():
# Not a string, empty or only whitespaces
return

# Do the actual parse action
try:
text = fdate.parse(format, tz_in, tz_out)
except Exception as e:
sublime.error_message("[InsertDate]\n%s: %s" % (type(e).__name__, e))
status('Error parsing format string', e)
return

# Don't bother replacing selections with actually nothing
if text == '' or text.isspace():
return

# Fix potential unicode/codepage issues
if ST2 and isinstance(text, str):
try:
text = text.decode(locale.getpreferredencoding())
except UnicodeDecodeError:
text = text.decode('utf-8')

# Do replacements
for r in self.view.sel():
# Insert when sel is empty to not select the contents
Expand All @@ -186,6 +185,57 @@ def run(self, edit, format=None, prompt=False, tz_in=None, tz_out=None):
self.view.replace(edit, r, text)


class InsertDatePanelCommand(sublime_plugin.TextCommand):
"""Shows a quick panel with pre-defined and configurable templates that are previewed
"""
panel_cache = []
config_map = {}

def run(self, edit, tz_in=None, tz_out=None):
self.panel_cache = []
self.config_map = {}

if not isinstance(s.prompt_config, list):
status("`prompt_config` setting is invalid")
return

configs = s.prompt_config
if not isinstance(s.user_prompt_config, list):
status("`user_prompt_config` setting is invalid")
else:
configs.extend(s.user_prompt_config)

# Generate panel cache for quick_panel
for conf in configs:
# Read config
c = dict()
c['tz_in'] = tz_in if tz_in else conf.get('tz_in')
c['tz_out'] = tz_out if tz_out else conf.get('tz_out')
c['format'] = conf.get('format')

if isinstance(c['format'], basestring):
c['format'] = c['format'].replace("$default", fdate.default['format'])

# Do the actual parse action
try:
text = fdate.parse(**c)
except Exception as e:
status('Error parsing format string', e)
return

self.panel_cache.append([conf['name'], text])
self.config_map[conf['name']] = c

self.view.window().show_quick_panel(self.panel_cache, self.on_done)

def on_done(self, index):
if index == -1:
return

name = self.panel_cache[index][0]
self.view.run_command("insert_date", self.config_map[name])


# Handle context
def plugin_loaded():
global s, fdate
Expand All @@ -194,7 +244,9 @@ def plugin_loaded():
sublime.load_settings('insert_date.sublime-settings'),
settings=dict(
format=('format', '%c'),
tz_in=('tz_in', 'local')
tz_in=('tz_in', 'local'),
prompt_config=None,
user_prompt_config=None
)
)

Expand Down
65 changes: 63 additions & 2 deletions insert_date.sublime-settings
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,66 @@
// of now, 'local' does not support the `%Z` named timezone representation
// and it is HIGHLY RECOMMENDED to specify your local pytz timezone here.
// Default: 'local'
"tz_in": "local"
}
"tz_in": "local",

// A set of pre-defined settings that are prompted by "promt_insert_time"
// and previewed. You can modify this list in your User settings, but be
// aware that you remove all these entries when overriding "prompt_config"!
// Use "user_prompt_config" if you just want to add a few entries.
//
// `$default` is replaced by the "format" setting above, unspecified values
// remain default.
"prompt_config": [
// Default timezone and formats
{ "name": "Default"
},
{ "name": "Time",
"format": "%X"
},
{ "name": "Date",
"format": "%x"
},
// UTC, iso (standards)
{ "name": "UTC",
"tz_out": "UTC"
},
{ "name": "UTC+",
"format": "$default (UTC%z)",
"tz_out": "UTC"
},
{ "name": "iso",
"format": "iso"
},
{ "name": "UTC iso",
"format": "iso",
"tz_out": "UTC"
},
// Popular timezones
{ "name": "EST",
"tz_out": "EST"
},
{ "name": "EST+",
"format": "$default (UTC%z)",
"tz_out": "EST"
},
{ "name": "PST",
"tz_out": "PST8PDT"
},
{ "name": "PST+",
"format": "$default (UTC%z)",
"tz_out": "PST8PDT"
},
{ "name": "CET",
"tz_out": "CET"
},
{ "name": "CET+",
"format": "$default (UTC%z)",
"tz_out": "CET"
}
],

// Works similar to "prompt_config" but is added to the above list.
// Supposed to be used by you when you just want to add some entries to the
// list.
"user_prompt_config": []
}

0 comments on commit 24a0cc5

Please sign in to comment.