Home Download Buy Blog Forum Support



Postby mimik on Mon Jun 24, 2013 3:17 pm


I wan't to record the amount of code i write with sublime.
How can i get the filetype of an open file?

And is there away i can save the number to a file or storage?

now i have this:

Code: Select all
import sublime, sublime_plugin
count = 0
class CodeStats(sublime_plugin.EventListener):
   clicks = 0
   clicksTrigger = 10
   count = 0
   file_name = ''

   def on_modified(self, view):
      self.clicks += 1
      self.count += 1
      if self.clicks >= self.clicksTrigger:
   def showStats(self):
      print "code written", self.count
      self.clicks = 0

As of now i just call the print function every 10 keystrokes.
Got any tips or ideas?
Oh and is there away for me to code this is JS instead of Python? 8-)
Posts: 3
Joined: Wed Dec 28, 2011 10:36 am

Re: CodeTracking

Postby miped on Mon Jul 08, 2013 7:36 pm

There are a couple of ways to get at the current syntax file (i.e. file type).

First, you could just use the file name of the current view, and then parse the extension. This will work for most languages:
Code: Select all

Which returns something like u'/Users/mp/Desktop/untitled.php'
Then you can use os.path.splitext to get the extension from that.

Alternatively, you can look at the syntax for the file:
Code: Select all

Which would return the following for a php file: u'Packages/PHP/PHP.tmLanguage' and it has the benefit of working with unsaved files.

Lastly, you could also try and find the current scope of the view (0 is the first character in the view, you might want to replace with something like view.sel()[0].begin()):
Code: Select all

Which returns this for python: u'source.python ' but this for php: u'text.html.basic '. This has the benefit of working inside script blocks in html for instance, or with mixed html / css /php / whatever.

So you might have to do a little bit of logic combining the three methods. Also remember that doing something on EVERY modification might make your editor a little slow. Personally, when i need a count of the code i've written i turn to the cloc program from http://cloc.sourceforge.net/. It has classifiers for most languages, and is very flexible. But i write all my code in Sublime Text, so i know that if it's written by me it's in Sublime Text. YMMV :-)
SublimeGit: Git integration for Sublime Text 2 and 3
Posts: 16
Joined: Mon Jul 08, 2013 6:30 pm

Return to Plugin Development

Who is online

Users browsing this forum: Yahoo [Bot] and 5 guests