Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday, December 3, 2014

Notepad++ Language Selector


Notepad++ Language Selector

I keep code samples that I find useful as small text files. I store them as vanilla txt files as opposed to the language in which they are written so that they will open in Notepad++ (NPP) instead of the editor. In other words, I don't want my c++ examples to open in an IDE, just notepad.

Notepad++ has syntax highlighting for various languages, but it is based on the file type. Therefore, all my SQL examples show up as normal text. I thought it would be nice if I could have NPP select the language format based on a simple keyword in the text file.

I asked this question 4 years ago on stackoverflow (the answer was that it couldn’t be done), and then I realized I could achieve this goal using the python plugin! I’m going to assume you already know how to use the python plugin for NPP and how to setup your environment. If not, refer to my post about custom timestamps in NPP.


Walkthrough

The first line of the file will start with "##", followed by the menucommand code for that language

The 3 step process:

  1. Define a function that will switch the language after the file is opened
  2. Write a command that links your function to the “File Opened” notification in NPP
  3. Put it all together


Step 1 and 2: Define your function and link to notification


#if found determine the menu command and switch language in NPP
def switch_language_view(args):
    notepad.activateBufferID(args["bufferID"])
    lineone = editor.getLine(0)
    if '##' in lineone:
     lineone = lineone[lineone.rfind('##'):].replace('##', '')
     lineone = "MENUCOMMAND." + lineone.upper()
     try:
      notepad.menuCommand( eval(lineone) )
     except:
      pass

#command to link notification
notepad.callback(switch_language_view, [NOTIFICATION.FILEOPENED])

  • This script grabs the first line of the file and looks for the command. After it finds the ## tag, it tries to send the menu command to notepad
  • Quick note about args: you need the args so that the script gets access to the current file being opened. Otherwise (as I discovered) it will read the first line of your code instead!
  • The last line is a separate call that links your function with the NPP event NOTIFICATION.FILEOPENED


Step 3: Put it all together

You have to place the code (both parts) in a special python script that will run when NPP starts. It’s called startup.py, and I pasted the above code at the end of that file, one after the other.

Some things to note about startup.py:
By default, this script is only run before you run your first python script. You want to change this behavior, so you need to change a configuration setting in the plugin.

  1. Menu: Plugins > Python Script > Configuration
  2. Switch Initialisation from “LAZY” to “ATSTARTUP” (there’s an explanation in the dialog)

On my PC, the startup.py script is located in the Program Files folder:
C:\Program Files (x86)\Notepad++\plugins\PythonScript\scripts\startup.py

This unfortunately means it might have some protective permissions. There are two things you could do to make your life somewhat easier:

  1. Open Notepad.exe (yes notepad) as an Administrator, which will allow you to save any changes
  2. Change the permissions on startup.py to allow Full Control for all users on your computer
I started out with option 1, but after some initial issues I switched to option 2 which made things much easier to debug using the Python Console in NPP.


Test Script

Setup the test script:

  1. Menu: Plugins > Python Script > New Python Script
  2. It will ask you for a new file name, I choose: switch_language.py
  3. A new tab will appear in NP++ for you to enter the script
  4. After saving, you should be able to run this code from the menu: Plugins > Python Script > Scripts > switch_language.py
  5. Make sure you have a test file active when you test the script!
  6. This script writes the result to the python console in NPP (make sure you have it displayed)


#This is the script I used (for testing):
#script to test switching language syntax of active file    
lineone = editor.getLine(0)
if '##' in lineone:
    lineone = lineone[lineone.rfind('##'):].replace('##', '')
    lineone = "MENUCOMMAND." + lineone.upper()
    try:
notepad.menuCommand( eval(lineone) )
   except:
     pass

console.write(lineone)


Example using the test script

Wednesday, November 19, 2014

Clipboard Timestamp

Clipboard Timestamp

Launchy that timestamp into your clipboard

.background

Looking back through my blog, one of my most popular posts was how to write a timestamp script for Notepad++ in Python. I've been finding myself wishing I had that feature in more and more place, including web apps.

I had the idea to write a script that would generate the timestamp I wanted, and then place it in the Windows clipboard. This would allow me to generate and paste a timestamp anywhere I wanted. I ended up writing 2 scripts, the first was in Python and later I wrote a second in Powershell. Each as their advantages and disadvantages detailed below.

.launch

I tried a few techniques for calling the script, but in the end I settled on a tool I already use, called Launchy. Launchy is a super-simple (cross platform) application launcher with some powerful extra features. One of these features is that it can call scripts, and it even gives focus back to the application I was using after it is done!

http://www.launchy.net

.python

It's extremely safe to say that I don't know Python, but I've been programming since I was very little so I know how to hack around a language. It took me longer to figure out the little intricacies of the language than to write the actual script. I found an example on stackoverflow and then incorporated it with my existing code from Notepad++.

The Python community has a couple different ways of accessing the clipboard, but the one I liked best was to use a built-in GUI library called Tkinter. I don't like having to install a separate library when a built-in method is available.

When you run the script, a command window flashes temporarily, which was annoying. In Windows just rename your script to “.pyw” to avoid this. There are similar solutions for other platforms, just in case you are interested.

You have to have Python installed for this script to work, which could be a big downside if you don't already have it installed. I don't have a problem with this, but I have a hard time recommending a script that requires that you install a toolset you may never use for anything else.

# cdate.pyw
# add date/time to clipboard
# output example: 10/14/2014 JMJ
import time, sys
s_time = "%s JMJ" % (time.strftime('%m-%d-%Y'))

#s_time contains the timestamp text, now add it to the clipboard
from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append(s_time)
r.destroy()

sys.exit(0)


references:
http://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python/4203897#4203897
http://stackoverflow.com/questions/1689015/run-python-script-without-dos-shell-appearing

.powershell

While researching how to link my python script into Launchy, I ran into an article explaining how to launch powershell commands. It made a lot of sense to write the same script in Powershell, since no additional software would be required.

Powershell has a command called “clip” that allows you to pipe text directly into the Windows clipboard. Very nice. I had the command written in just a few minutes.

However, powershell scripts do not like to run without opening a command window. It is very annoying. I ended up using a technique where you create a VBS script (!!!) to call the powershell command. I feel weird about using VBS in this way, but it works. Unfortunately it requires you add a bunch of quotes to escape out all the layers of script calls (VBS > CMD > PowerShell). If you don't care about initials you can remove that part entirely. If your initials are “JMJ” perhaps you have it best of all.


‘pclip.vbs
'add date/time to clipboard via powershell (yes, there are a lot of escaped quotes in this code)
‘output example: 10/14/2014 JMJ
command = "powershell.exe -nologo -command (get-date -format d).ToString() + """""" JMJ"""""" | clip "
set shell = CreateObject("WScript.Shell")
shell.Run command,0


references:
http://technet.microsoft.com/en-us/library/ee692801.aspx
http://www.faqforge.com/windows/how-to-execute-powershell-scripts-without-pop-up-window

.set up Launchy

  1. Under the Launchy options, switch to the Catalog tab.
  2. Add a new Directory (+), and include the folder where your scripts are located.
  3. Under File Types, enter either *.pyw or *.vbs (depending on which solution you went with)

The great thing about Launchy is that it will return focus to the application I was using after I run the script. This makes the script very easy to call from other programs and online apps.

.wrap-up

I can't decide which is going to be more useful, having a simple timestamp available inside any program or website I'm using, or the fact that I can build more scripts and run them very easily through Launchy.

Monday, March 25, 2013

Notepad++ Time-Stamp

Kudos

I’ve been keeping some form of a work journal for years; I’d highly recommend it.  I recently got annoyed with creating timestamps in Notepad++, and ran across a helpful post in a forum.  It was so helpful that I thought I’d do my best to try to give it some additional street cred.

Here is the original link:
http://sourceforge.net/p/notepad-plus/discussion/331753/thread/3458d1da#62f2

What day of the week was 4/22/2006 anyway?

Before I start, if you have the TextFX plugin already setup in Notepad++, it provides 2 static methods of inserting a datetime stamp:
Menu: TextFX > TextFX Insert > I:Date & Time: short format: 3:56 PM 3/22/2013
Menu: TextFX > TextFX Insert > I:Date & Time: long format:  3:56 PM Friday, March 22, 2013
If these look good enough to you, you can skip to the section on how to map a keyboard shortcut to these.  However, in addition to the time and date, I also wanted the day of the week, like this:
03:36 PM 03/22/2013 (Friday)


Steps

It turns out this can easily be done with a simple Python script.  I don’t even know Python that well and I was able to do it.

1. Install the python plugin:
  • The plugin’s name is: Python Script
  • It’s recommend you do this via the NP++ Plugin Manger (Menu: Plugins > Plugin Manger)
  • Here’s a link to the project page:  http://npppythonscript.sourceforge.net/
  • The script includes some basic Python libraries, so you shouldn’t need to install Python or other 3rd party libraries

2. Setup script in Notepad++:
  • Menu:  Plugins > Python Script > New Python Script
  • It will ask you for a new file name, I choose: npp_timedate_stamp.py
  • A new tab will appear in NP++ for you to enter the script.
  • This is the script I used:
    
    # Add date/time stamp in Notepad++ 03:28 PM 03-22-2013 (Friday)
    import time
    editor.addText( time.strftime( '%I:%M %p %m/%d/%Y (%A) ' ) )
    
    
  • Here is a link to the Python documentation which shows what all the format string characters: http://docs.python.org/2/library/time.html
  • Save your script

3. Configure Notepad++ to use the script:
  • Menu: Plugins > Python Script > Configuration
  • You should see your script under the User Scripts section
  • Add it to Toolbar and/or Menu
  • I put it in both, but I only managed to find it under menu
  • It shows up as its own entry under Menu: Plugins > Python Script > npp_timedate_stamp

4. Create a keyboard shortcut (my preferred method):
  • Menu: Settings > Shortcut Mapper
  • Switch to Plugin
  • Scroll down until you see your script name (i.e. npp_timedate_stamp)
  • Click on it, choose Modify, and choose a key.  I used: CTRL + ;

Furthermore

This was exciting to me in more ways than one, because in the past I’ve looked for ways of modifying Notepad++, and plugins can be a daunting undertaking.  Apparently the Python plugin is mapped to all the Notepad++ features, so I might utilize it more in the future.