SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
Write Sublime
Text 2 Packages
with Python
Jenny JS Liang (jsliang)
PyConTW 2013
About 梁睿珊 / Jenny /
jsliang
http://github.com/jsliang
2006~2012
Student (undergraduate & graduate) @
NCTU CS
2012~present
Software Engineer @ IBM Taiwan
Joined Python user community since PyHUG
Feb meeting, 2012
Why I like Sublime Text 2?
http://www.sublimetext.com/ - the home page
shows you why.
1. Fuzzy match of...
a. Goto Anything (Ctrl + P)
b. Command Palette (Ctrl + Shift + P)
2. Multiple Selections/Edits
3. Cross Platform (OSX, Windows & Linux)
4. Python-style regular expression
5. Python Plugin API
I'll use "ST2" for "Sublime Text 2" from now on.
Where do you place your
packages?
● Menu bar > Preferences > Browse
Packages...
● On package per folder
○ Packages/
■ MyPackage/
● *.py
○ Commands or EventListeners
● *.sublime-macro
● *.sublime-menu
● *.sublime-keymap
● *.sublime-snippet
● ...
Tip: check out files under Packages/Default/
Hello World - Your 1st
Command
Menu bar > Tools > New Plugin...
import sublime, sublime_plugin
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.insert(edit, 0, "Hello, World!")
Save to: Packages/HelloWorld/HelloWorld.py
Hello World - Executing
Command
1. Restart ST2
2. Start Sublime Console by pressing Ctrl + `
3. Type in console:
○ view.run_command('example')
4. A "Hello World" string is inserted to the
beginning of the view
Command Naming Rules
Each command is a subclass of sublime_plugin.
*Command. When naming, use CamelCase +
"Command".
class HelloWorldCommand
(sublime_plugin.TextCommand):
...
To use the command, use underscore_notation:
view.run_command('hello_world')
Types of Commands
1. Class sublime_plugin.ApplicationCommand
○ run(<args>)
○ institiated when ST2 is launched
2. Class sublime_plugin.WindowCommand
○ run(<args>)
○ instantiated once per window
○ self.window
3. Class sublime_plugin.TextCommand
○ run(edit, <args>)
○ instantiated once per view
○ self.view
Hierarchy: Application > Window > Text
Make Your Command more
Accessible (*.sublime-commands)
[
{ "caption": "AutoJump: Open a File in a Visited Folder",
"command": "autojump_traverse_visited_folder" }
,{ "caption": "AutoJump: Open a Recent File",
"command": "autojump_open_recent_file" }
]
Key Binding (Default.
sublime-keymap)
[
{"keys": ["ctrl+alt+j"],
"command": "autojump_traverse_visited_folder"}
, {"keys": ["ctrl+alt+k"],
"command": "autojump_open_recent_file"}
]
Key Binding on different
OS
Default.sublime-keymap
Default (Linux).sublime-keymap
Default (OSX).sublime-keymap
Default (Windows).sublime-keymap
Menu Entries
● Main.sublime-menu
○ Main program menu
● Context.sublime-menu
○ Context menu (right clicking on a file)
● Side Bar.sublime-menu
○ Side bar menu (right clicking on a file/folder in
sidebar)
Each menu is a list of dicts, and each dict
describes a command or separator.
Main Menu
Side Bar Menu & Context
Menu
Add Command to Menu
Entries
Follow the structure in Packages/Default/*.sublime-menu
and insert your entry to your desired place. Save as Main.
sublime-menu under package folder.
[{
"id": "edit", "children": [
{"id": "mark"},
{
"command": "hello_world",
"mnemonic": "h",
"caption": "Hello below Mark"
}
]
}]
Event Listener
Each event listener is a subclass of
sublime_plugin.EventListener.
import sublime, sublime_plugin
class ViewClose(sublime_plugin.
EventListener):
def on_close(self, view):
sublime.message_dialog("View closed.")
Event Listener Methods
● on_new(view)
● on_clone(view)
● on_load(view)
● on_close(view)
● on_pre_save(view)
● on_post_save(view)
● on_modified(view)
● on_selection_modified(view)
● on_activated(view) - on focus
● on_deactivated(view) - on blur
● on_query_context(view, key, operator, operand,
match_all)
Quick Panel
● Similar to command palette
● Triggered by a ST2 window
Quick Panel
class ShowQuickPanelCommand
(sublime_plugin.WindowCommand):
def run(self):
self.window.show_quick_panel(mylist,
self.on_done)
def on_done(self, picked):
sublime.message_dialog( mylist
[picked])
Package Settings
# Packages/MyPackage/MyPackage.sublime-settings
base_name = "MyPackage.sublime-settings"
pkg_settings = sublime.load_settings(base_name)
myvar = pkg_settings.get("myvar",
"default_value")
pkg_settings.set("myvar", "new value")
sublime.save_settings(base_name)
Package Setting Files
Packages/
● MyPackage/
○ MyPackage.sublime-settings # default settings
○ Main.sublime-menu
○ ...
● User/
○ MyPackage.sublime-settings # user-customized
settings
○ ...
Add Package Setting
Option to Main Menu
● "id": "preferences", "children":
○ "id": "package-settings", "children":
■ "caption": "MyPackage",
■ "children":
● "command": "open_file",
"args": {"file": "${packages}
/MyPackage/MyPackage.sublime-
settings"},
"caption": "Settings – Default"
● "command": "open_file",
"args": {"file": "${packages}
/User/MyPackage.sublime-settings"},
"caption": "Settings – User"
Manipulating Selections /
Regions
sel_regionset = view.sel()
# sel_regionset is a RegionSet object
visible_region = view.
visible_region()
# visible_region is a Region object
substr() / erase() / replace() / line() /
split_by_newlines() / word() / show() /
show_at_center() / ...
Example Plugins
● Packages/Default/delete_word.py
○ Deletes a word to the left or right of the cursor
● Packages/Default/duplicate_line.py
○ Duplicates the current line
● Packages/Default/goto_line.py
○ Prompts the user for input, then updates the
selection
● Packages/Default/font.py
○ Shows how to work with settings
● Packages/Default/mark.py
○ Uses add_regions() to add an icon to the gutter
● Packages/Default/trim_trailing_whitespace.py
○ Modifies a buffer just before its saved
How to share my ST2
packages?
1. Compress your package folder to a file and
let other people download it
○ do not forget to add a README telling users the
extracting destination
2. Similar to 1, put your package on
GitHub/Gitorious so that others can clone it.
3. If you think the above methods are too
geekish...
You must try Will Bond's Sublime Package
Control
Sublime Package Control
by wbond (1/2)
Sublime Package Control
by wbond (2/2)
http://wbond.
net/sublime_packages/package_control
● a ST2 package that manages your installed
ST2 packages
● search for and install ST2 packages
○ http://wbond.net/sublime_packages/community
○ http://wbond.
net/sublime_packages/package_control/usage
● If you want your ST2 package to be found by
Sublime Package Control...
○ http://wbond.
net/sublime_packages/package_control/package_de
References
http://www.sublimetext.
com/docs/2/api_reference.html - must
reference!
http://net.tutsplus.com/tutorials/python-
tutorials/how-to-create-a-sublime-text-2-plugin/
- quick start

Mais conteúdo relacionado

Mais procurados

New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...alessandro mazzoli
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Mail.ru Group
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHPmarkstory
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQueryorestJump
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway ichikaway
 
Building Your First Widget
Building Your First WidgetBuilding Your First Widget
Building Your First WidgetChris Wilcoxson
 
Drupal module development
Drupal module developmentDrupal module development
Drupal module developmentDamjan Cvetan
 
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Puppet
 

Mais procurados (19)

Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
 
Lumberjack XPath 101
Lumberjack XPath 101Lumberjack XPath 101
Lumberjack XPath 101
 
Cpsh sh
Cpsh shCpsh sh
Cpsh sh
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQuery
 
jQuery
jQueryjQuery
jQuery
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
 
Building Your First Widget
Building Your First WidgetBuilding Your First Widget
Building Your First Widget
 
занятие8
занятие8занятие8
занятие8
 
Drupal module development
Drupal module developmentDrupal module development
Drupal module development
 
Unfiltered Unveiled
Unfiltered UnveiledUnfiltered Unveiled
Unfiltered Unveiled
 
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
 
Perl5i
Perl5iPerl5i
Perl5i
 

Destaque

Improve Yield Accounting by including Density Measurements Explicitly
Improve Yield Accounting by including Density Measurements ExplicitlyImprove Yield Accounting by including Density Measurements Explicitly
Improve Yield Accounting by including Density Measurements ExplicitlyAlkis Vazacopoulos
 
Презентація команди Васильківської ЗОШ І-ІІІ ступенів №1
Презентація команди Васильківської ЗОШ І-ІІІ ступенів №1Презентація команди Васильківської ЗОШ І-ІІІ ступенів №1
Презентація команди Васильківської ЗОШ І-ІІІ ступенів №108600 Vasilkov
 
Impulse!final inauguracion
Impulse!final inauguracionImpulse!final inauguracion
Impulse!final inauguracionorbitalight
 
نهائي العروض
نهائي العروضنهائي العروض
نهائي العروضFJRFJR
 
La salvacion parte_2
La salvacion parte_2La salvacion parte_2
La salvacion parte_2Tito Ortega
 
Advanced Production Accounting of a Flotation Plant
Advanced Production Accounting of a Flotation PlantAdvanced Production Accounting of a Flotation Plant
Advanced Production Accounting of a Flotation PlantAlkis Vazacopoulos
 
Презентация Васильківської ЗОШ І-ІІІ ст№9 "Вулиця Бурки"
Презентация Васильківської ЗОШ І-ІІІ ст№9 "Вулиця Бурки"Презентация Васильківської ЗОШ І-ІІІ ст№9 "Вулиця Бурки"
Презентация Васильківської ЗОШ І-ІІІ ст№9 "Вулиця Бурки"08600 Vasilkov
 
Самаврядування васильківської ЗОШ І-ІІІ ступенів № 1
Самаврядування васильківської ЗОШ І-ІІІ ступенів № 1Самаврядування васильківської ЗОШ І-ІІІ ступенів № 1
Самаврядування васильківської ЗОШ І-ІІІ ступенів № 108600 Vasilkov
 
New Retargeting Strategies for 2014
New Retargeting Strategies for 2014New Retargeting Strategies for 2014
New Retargeting Strategies for 2014Dispop
 
Stock Decomposition Heuristic for Scheduling: A Priority Dispatch Rule Approach
Stock Decomposition Heuristic for Scheduling: A Priority Dispatch Rule ApproachStock Decomposition Heuristic for Scheduling: A Priority Dispatch Rule Approach
Stock Decomposition Heuristic for Scheduling: A Priority Dispatch Rule ApproachAlkis Vazacopoulos
 
Hybrid Dynamic Simulation (HDS) Industrial Modeling Framework (HDS-IMF)
Hybrid Dynamic Simulation (HDS)  Industrial Modeling Framework (HDS-IMF)Hybrid Dynamic Simulation (HDS)  Industrial Modeling Framework (HDS-IMF)
Hybrid Dynamic Simulation (HDS) Industrial Modeling Framework (HDS-IMF)Alkis Vazacopoulos
 
Pp reunión pedagógica-3°-4° básicos 2016
Pp reunión pedagógica-3°-4° básicos 2016Pp reunión pedagógica-3°-4° básicos 2016
Pp reunión pedagógica-3°-4° básicos 2016Emmanuel High School
 
Презентация Васильківської ЗОШ І-ІІІ ст№8 "Військове містечко11""
Презентация Васильківської ЗОШ І-ІІІ ст№8 "Військове містечко11""Презентация Васильківської ЗОШ І-ІІІ ст№8 "Військове містечко11""
Презентация Васильківської ЗОШ І-ІІІ ст№8 "Військове містечко11""08600 Vasilkov
 
My Certificates - Volume 1
My Certificates - Volume 1My Certificates - Volume 1
My Certificates - Volume 1Tony Campanale
 

Destaque (20)

Improve Yield Accounting by including Density Measurements Explicitly
Improve Yield Accounting by including Density Measurements ExplicitlyImprove Yield Accounting by including Density Measurements Explicitly
Improve Yield Accounting by including Density Measurements Explicitly
 
Презентація команди Васильківської ЗОШ І-ІІІ ступенів №1
Презентація команди Васильківської ЗОШ І-ІІІ ступенів №1Презентація команди Васильківської ЗОШ І-ІІІ ступенів №1
Презентація команди Васильківської ЗОШ І-ІІІ ступенів №1
 
Impulse!final inauguracion
Impulse!final inauguracionImpulse!final inauguracion
Impulse!final inauguracion
 
Goal setting - dr. s. swapna kumar
Goal  setting - dr. s. swapna kumarGoal  setting - dr. s. swapna kumar
Goal setting - dr. s. swapna kumar
 
نهائي العروض
نهائي العروضنهائي العروض
نهائي العروض
 
La salvacion parte_2
La salvacion parte_2La salvacion parte_2
La salvacion parte_2
 
Advanced Production Accounting of a Flotation Plant
Advanced Production Accounting of a Flotation PlantAdvanced Production Accounting of a Flotation Plant
Advanced Production Accounting of a Flotation Plant
 
Pasapalabra, marc i akaki
Pasapalabra, marc i akakiPasapalabra, marc i akaki
Pasapalabra, marc i akaki
 
Test powerpoint
Test powerpointTest powerpoint
Test powerpoint
 
Console manual impl
Console manual implConsole manual impl
Console manual impl
 
Презентация Васильківської ЗОШ І-ІІІ ст№9 "Вулиця Бурки"
Презентация Васильківської ЗОШ І-ІІІ ст№9 "Вулиця Бурки"Презентация Васильківської ЗОШ І-ІІІ ст№9 "Вулиця Бурки"
Презентация Васильківської ЗОШ І-ІІІ ст№9 "Вулиця Бурки"
 
Самаврядування васильківської ЗОШ І-ІІІ ступенів № 1
Самаврядування васильківської ЗОШ І-ІІІ ступенів № 1Самаврядування васильківської ЗОШ І-ІІІ ступенів № 1
Самаврядування васильківської ЗОШ І-ІІІ ступенів № 1
 
Assessment p health
Assessment p healthAssessment p health
Assessment p health
 
New Retargeting Strategies for 2014
New Retargeting Strategies for 2014New Retargeting Strategies for 2014
New Retargeting Strategies for 2014
 
Stock Decomposition Heuristic for Scheduling: A Priority Dispatch Rule Approach
Stock Decomposition Heuristic for Scheduling: A Priority Dispatch Rule ApproachStock Decomposition Heuristic for Scheduling: A Priority Dispatch Rule Approach
Stock Decomposition Heuristic for Scheduling: A Priority Dispatch Rule Approach
 
Hybrid Dynamic Simulation (HDS) Industrial Modeling Framework (HDS-IMF)
Hybrid Dynamic Simulation (HDS)  Industrial Modeling Framework (HDS-IMF)Hybrid Dynamic Simulation (HDS)  Industrial Modeling Framework (HDS-IMF)
Hybrid Dynamic Simulation (HDS) Industrial Modeling Framework (HDS-IMF)
 
Pp reunión pedagógica-3°-4° básicos 2016
Pp reunión pedagógica-3°-4° básicos 2016Pp reunión pedagógica-3°-4° básicos 2016
Pp reunión pedagógica-3°-4° básicos 2016
 
Презентация Васильківської ЗОШ І-ІІІ ст№8 "Військове містечко11""
Презентация Васильківської ЗОШ І-ІІІ ст№8 "Військове містечко11""Презентация Васильківської ЗОШ І-ІІІ ст№8 "Військове містечко11""
Презентация Васильківської ЗОШ І-ІІІ ст№8 "Військове містечко11""
 
農林白書
農林白書農林白書
農林白書
 
My Certificates - Volume 1
My Certificates - Volume 1My Certificates - Volume 1
My Certificates - Volume 1
 

Semelhante a [PyConTW 2013] Write Sublime Text 2 Packages with Python

Python-GTK
Python-GTKPython-GTK
Python-GTKYuren Ju
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
The beautyandthebeast phpbat2010
The beautyandthebeast phpbat2010The beautyandthebeast phpbat2010
The beautyandthebeast phpbat2010Bastian Feder
 
Python GTK (Hacking Camp)
Python GTK (Hacking Camp)Python GTK (Hacking Camp)
Python GTK (Hacking Camp)Yuren Ju
 
Automation and Ansible
Automation and AnsibleAutomation and Ansible
Automation and Ansiblejtyr
 
Spin Up Desktop Apps with Electron.js
Spin Up Desktop Apps with Electron.jsSpin Up Desktop Apps with Electron.js
Spin Up Desktop Apps with Electron.jsSteve Godin
 
How to became a Gentoo developer
How to became a Gentoo developerHow to became a Gentoo developer
How to became a Gentoo developeralice ferrazzi
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android DevelopmentJussi Pohjolainen
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for BeginnersArie Bregman
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsOWASP Kyiv
 
IzPack at LyonJUG'11
IzPack at LyonJUG'11IzPack at LyonJUG'11
IzPack at LyonJUG'11julien.ponge
 
Reproducible Computational Research in R
Reproducible Computational Research in RReproducible Computational Research in R
Reproducible Computational Research in RSamuel Bosch
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with pythonroskakori
 
Git the Docs: Learning Git in a safe space
Git the Docs: Learning Git in a safe spaceGit the Docs: Learning Git in a safe space
Git the Docs: Learning Git in a safe spaceBecky Todd
 

Semelhante a [PyConTW 2013] Write Sublime Text 2 Packages with Python (20)

Python-GTK
Python-GTKPython-GTK
Python-GTK
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
The beautyandthebeast phpbat2010
The beautyandthebeast phpbat2010The beautyandthebeast phpbat2010
The beautyandthebeast phpbat2010
 
Python GTK (Hacking Camp)
Python GTK (Hacking Camp)Python GTK (Hacking Camp)
Python GTK (Hacking Camp)
 
Automation and Ansible
Automation and AnsibleAutomation and Ansible
Automation and Ansible
 
Spin Up Desktop Apps with Electron.js
Spin Up Desktop Apps with Electron.jsSpin Up Desktop Apps with Electron.js
Spin Up Desktop Apps with Electron.js
 
R sharing 101
R sharing 101R sharing 101
R sharing 101
 
How to became a Gentoo developer
How to became a Gentoo developerHow to became a Gentoo developer
How to became a Gentoo developer
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for Beginners
 
Ext 0523
Ext 0523Ext 0523
Ext 0523
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
 
Flash develop presentation
Flash develop presentationFlash develop presentation
Flash develop presentation
 
Devtools cheatsheet
Devtools cheatsheetDevtools cheatsheet
Devtools cheatsheet
 
Devtools cheatsheet
Devtools cheatsheetDevtools cheatsheet
Devtools cheatsheet
 
IzPack at LyonJUG'11
IzPack at LyonJUG'11IzPack at LyonJUG'11
IzPack at LyonJUG'11
 
Reproducible Computational Research in R
Reproducible Computational Research in RReproducible Computational Research in R
Reproducible Computational Research in R
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with python
 
Git the Docs: Learning Git in a safe space
Git the Docs: Learning Git in a safe spaceGit the Docs: Learning Git in a safe space
Git the Docs: Learning Git in a safe space
 

Último

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

[PyConTW 2013] Write Sublime Text 2 Packages with Python

  • 1. Write Sublime Text 2 Packages with Python Jenny JS Liang (jsliang) PyConTW 2013
  • 2. About 梁睿珊 / Jenny / jsliang http://github.com/jsliang 2006~2012 Student (undergraduate & graduate) @ NCTU CS 2012~present Software Engineer @ IBM Taiwan Joined Python user community since PyHUG Feb meeting, 2012
  • 3. Why I like Sublime Text 2? http://www.sublimetext.com/ - the home page shows you why. 1. Fuzzy match of... a. Goto Anything (Ctrl + P) b. Command Palette (Ctrl + Shift + P) 2. Multiple Selections/Edits 3. Cross Platform (OSX, Windows & Linux) 4. Python-style regular expression 5. Python Plugin API I'll use "ST2" for "Sublime Text 2" from now on.
  • 4. Where do you place your packages? ● Menu bar > Preferences > Browse Packages... ● On package per folder ○ Packages/ ■ MyPackage/ ● *.py ○ Commands or EventListeners ● *.sublime-macro ● *.sublime-menu ● *.sublime-keymap ● *.sublime-snippet ● ... Tip: check out files under Packages/Default/
  • 5. Hello World - Your 1st Command Menu bar > Tools > New Plugin... import sublime, sublime_plugin class ExampleCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.insert(edit, 0, "Hello, World!") Save to: Packages/HelloWorld/HelloWorld.py
  • 6. Hello World - Executing Command 1. Restart ST2 2. Start Sublime Console by pressing Ctrl + ` 3. Type in console: ○ view.run_command('example') 4. A "Hello World" string is inserted to the beginning of the view
  • 7. Command Naming Rules Each command is a subclass of sublime_plugin. *Command. When naming, use CamelCase + "Command". class HelloWorldCommand (sublime_plugin.TextCommand): ... To use the command, use underscore_notation: view.run_command('hello_world')
  • 8. Types of Commands 1. Class sublime_plugin.ApplicationCommand ○ run(<args>) ○ institiated when ST2 is launched 2. Class sublime_plugin.WindowCommand ○ run(<args>) ○ instantiated once per window ○ self.window 3. Class sublime_plugin.TextCommand ○ run(edit, <args>) ○ instantiated once per view ○ self.view Hierarchy: Application > Window > Text
  • 9. Make Your Command more Accessible (*.sublime-commands) [ { "caption": "AutoJump: Open a File in a Visited Folder", "command": "autojump_traverse_visited_folder" } ,{ "caption": "AutoJump: Open a Recent File", "command": "autojump_open_recent_file" } ]
  • 10. Key Binding (Default. sublime-keymap) [ {"keys": ["ctrl+alt+j"], "command": "autojump_traverse_visited_folder"} , {"keys": ["ctrl+alt+k"], "command": "autojump_open_recent_file"} ]
  • 11. Key Binding on different OS Default.sublime-keymap Default (Linux).sublime-keymap Default (OSX).sublime-keymap Default (Windows).sublime-keymap
  • 12. Menu Entries ● Main.sublime-menu ○ Main program menu ● Context.sublime-menu ○ Context menu (right clicking on a file) ● Side Bar.sublime-menu ○ Side bar menu (right clicking on a file/folder in sidebar) Each menu is a list of dicts, and each dict describes a command or separator.
  • 14. Side Bar Menu & Context Menu
  • 15. Add Command to Menu Entries Follow the structure in Packages/Default/*.sublime-menu and insert your entry to your desired place. Save as Main. sublime-menu under package folder. [{ "id": "edit", "children": [ {"id": "mark"}, { "command": "hello_world", "mnemonic": "h", "caption": "Hello below Mark" } ] }]
  • 16. Event Listener Each event listener is a subclass of sublime_plugin.EventListener. import sublime, sublime_plugin class ViewClose(sublime_plugin. EventListener): def on_close(self, view): sublime.message_dialog("View closed.")
  • 17. Event Listener Methods ● on_new(view) ● on_clone(view) ● on_load(view) ● on_close(view) ● on_pre_save(view) ● on_post_save(view) ● on_modified(view) ● on_selection_modified(view) ● on_activated(view) - on focus ● on_deactivated(view) - on blur ● on_query_context(view, key, operator, operand, match_all)
  • 18. Quick Panel ● Similar to command palette ● Triggered by a ST2 window
  • 19. Quick Panel class ShowQuickPanelCommand (sublime_plugin.WindowCommand): def run(self): self.window.show_quick_panel(mylist, self.on_done) def on_done(self, picked): sublime.message_dialog( mylist [picked])
  • 20. Package Settings # Packages/MyPackage/MyPackage.sublime-settings base_name = "MyPackage.sublime-settings" pkg_settings = sublime.load_settings(base_name) myvar = pkg_settings.get("myvar", "default_value") pkg_settings.set("myvar", "new value") sublime.save_settings(base_name)
  • 21. Package Setting Files Packages/ ● MyPackage/ ○ MyPackage.sublime-settings # default settings ○ Main.sublime-menu ○ ... ● User/ ○ MyPackage.sublime-settings # user-customized settings ○ ...
  • 22. Add Package Setting Option to Main Menu ● "id": "preferences", "children": ○ "id": "package-settings", "children": ■ "caption": "MyPackage", ■ "children": ● "command": "open_file", "args": {"file": "${packages} /MyPackage/MyPackage.sublime- settings"}, "caption": "Settings – Default" ● "command": "open_file", "args": {"file": "${packages} /User/MyPackage.sublime-settings"}, "caption": "Settings – User"
  • 23. Manipulating Selections / Regions sel_regionset = view.sel() # sel_regionset is a RegionSet object visible_region = view. visible_region() # visible_region is a Region object substr() / erase() / replace() / line() / split_by_newlines() / word() / show() / show_at_center() / ...
  • 24. Example Plugins ● Packages/Default/delete_word.py ○ Deletes a word to the left or right of the cursor ● Packages/Default/duplicate_line.py ○ Duplicates the current line ● Packages/Default/goto_line.py ○ Prompts the user for input, then updates the selection ● Packages/Default/font.py ○ Shows how to work with settings ● Packages/Default/mark.py ○ Uses add_regions() to add an icon to the gutter ● Packages/Default/trim_trailing_whitespace.py ○ Modifies a buffer just before its saved
  • 25. How to share my ST2 packages? 1. Compress your package folder to a file and let other people download it ○ do not forget to add a README telling users the extracting destination 2. Similar to 1, put your package on GitHub/Gitorious so that others can clone it. 3. If you think the above methods are too geekish... You must try Will Bond's Sublime Package Control
  • 27. Sublime Package Control by wbond (2/2) http://wbond. net/sublime_packages/package_control ● a ST2 package that manages your installed ST2 packages ● search for and install ST2 packages ○ http://wbond.net/sublime_packages/community ○ http://wbond. net/sublime_packages/package_control/usage ● If you want your ST2 package to be found by Sublime Package Control... ○ http://wbond. net/sublime_packages/package_control/package_de