Sublime Forum

CodeTracking

#1

Hello

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:

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:
			self.showStats()
	
	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? :sunglasses:

0 Likes

#2

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:

view.file_name()

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:

view.settings().get('syntax')

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()):

view.scope_name(0)

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 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 :smile:

0 Likes