Jump to content

Create script file from copied code


muncherw
 Share

Recommended Posts

I often copy code from the forums, create a new document, rename it, open it, paste the copied code in, and then save it. While that takes the entirety of 13 seconds to do there is still something I find tedious about it so I wrote this to save myself those valuable seconds. :D

Copy the code you want then run the script and it will create the file for you.

$fileName = InputBox("New AU3 Name", "What would you like to name the file?")
$file = FileOpen($fileName & ".au3", 10); Will create a new file and overwrite if already exists
If $file = -1 Then
   MsgBox(0, "Error", "Unable to open file.")
   Exit
EndIf
$fileContents = ClipGet()
FileWrite($file, $fileContents);Put the contents of the clipboard in the new file
FileClose($file)
Edited by muncherw
Other People's Stuff:Andy Flesner's AutoIt v3: Your Quick Guide[topic="34302"]Locodarwin's ExcelCom_UDF[/topic][topic="61090"]MrCreatorR's Opera Library[/topic]
Link to comment
Share on other sites

you should let it run in background, and then test the clipboard for the string au3 in the content, when its found, paste it to a new file, and

then set number for next script +1.

that would mean you would get a folder with script1.au3 script2.au3 and so on.

that way you just copy it , and forget it :D

but thats just my mind blowing away at the moment :D

Damian666

and proud of it!!!
Link to comment
Share on other sites

you should let it run in background, and then test the clipboard for the string au3 in the content, when its found, paste it to a new file, and

then set number for next script +1.

that would mean you would get a folder with script1.au3 script2.au3 and so on.

that way you just copy it , and forget it :D

but thats just my mind blowing away at the moment :P

Damian666

Actually, when I usually create a new script from a copied text I'd just right click and have it create a new file but then I have 5 new scripts all named with number increments and I don't know what any of them do. This was really created out of my laziness for not renaming files. Your idea would just cause me to automate the thing that makes me nuts. :D

Also I've noticed since I wrote this this morning that I use the clipboard a whole lot more than I ever realized,  so your idea of searching the text for au3 is a good one or I'd get 100 bogus script files.

Plus when I copy something from the forum I usually want to play with it right away. ;)

Other People's Stuff:Andy Flesner's AutoIt v3: Your Quick Guide[topic="34302"]Locodarwin's ExcelCom_UDF[/topic][topic="61090"]MrCreatorR's Opera Library[/topic]
Link to comment
Share on other sites

yeah, you do have a point there ^^

well, like i said, it is jut my mind blowing away :D

Damian666

If your mind comes up with a way to automatically assign a descriptive title so I don't even have to use the inputbox let me know. :D
Other People's Stuff:Andy Flesner's AutoIt v3: Your Quick Guide[topic="34302"]Locodarwin's ExcelCom_UDF[/topic][topic="61090"]MrCreatorR's Opera Library[/topic]
Link to comment
Share on other sites

well... actually... there s a way i believe...

as you proberly know, the page from which you would copy has a title...

what if we would be able to extract that title?

in theory it should work..., hmm...

Damian666

and proud of it!!!
Link to comment
Share on other sites

well... actually... there s a way i believe...

as you proberly know, the page from which you would copy has a title...

what if we would be able to extract that title?

in theory it should work..., hmm...

Damian666

A nice little script for the job. If the OP doesn't mind I tweaked it a bit to

optionally get the filename from the active window title as you suggested,

or pop up the input. Also made it a hotkey activated to avoid switching

away from the active window.

If the user opts to take the filename from the active window title I put

it through a Normalize function to get rid of spaces, percent signs and

other undesirable or illegal filename characters. Perhaps some heuristic

should be added to shorten the filename too, but stepwise refinement

and all that. :D

At the moment the hotkey is hard wired. I have a dialog for user selection

but I don't want to muddy up the idea with too much extraneous code right now.

$hotKey = "+{PgUp}";hotkey hard coded for test
HotKeySet($hotKey, "_DoPaste")

;sit in tray listening for hotkey
While 1
WEnd

Func _DoPaste()
    Local $folder = @ScriptDir & "\PastedScripts\"
    Local $initialFilename = WinGetTitle("[active]")
    Local $fileName = ""
    Local $msg = "Paste to filename: " & $fileName & @CRLF & "in folder: " & $folder
    Local $buttonPressed = MsgBox(0x1043, @ScriptName, $msg)
    If $buttonPressed = 2 Then
        Return
    ElseIf $buttonPressed = 7 Then
        $fileName = InputBox("New AU3 Name", "What would you like to name the file?")
    Else
        $fileName = _NormalizeFilename($initialFilename)
    EndIf
    $file = FileOpen($folder & $fileName & ".au3", 10)
    If $file = -1 Then
        MsgBox(0x1010, @ScriptName, "Unable to open file.")
        Return
    EndIf
    $fileContents = ClipGet()
    FileWrite($file, $fileContents);Put the contents of the clipboard in the new file
    FileClose($file)
EndFunc;==>_DoPaste

Func _NormalizeFilename($inFilename)
    Local Const $illegalFilenameChars = "?[]/\=+<>:;"",* %"
    Local $c = ""
    Local $fixedFilename = ""

    For $x = 1 To StringLen($inFilename)
        $c = StringMid($inFilename, $x, 1)
        If StringInStr($illegalFilenameChars, $c) Then
            $c = "_"
        EndIf
        $fixedFilename &= $c
    Next
    Return $fixedFilename
EndFunc;==>_NormalizeFilename
Edited by MilesAhead
Link to comment
Share on other sites

For now I just added a param to _NormalizeFilename to chop off the filename at $maxLen chars

;filter out percent signs, spaces, and illegal filename chars
;and substitute underscores. Optionally chop off return str
;at $maxLen chars.
;
;Author: MilesAhead
;
Func _NormalizeFilename($inFilename, $maxLen = 0)
    Local Const $illegalFilenameChars = "?[]/\=+<>:;"",* %"
    Local $c = ""
    Local $fixedFilename = ""

    For $x = 1 To StringLen($inFilename)
        $c = StringMid($inFilename, $x, 1)
        If StringInStr($illegalFilenameChars, $c) Then
            $c = "_"
        EndIf
        $fixedFilename &= $c
    Next
    If $maxLen Then
        Return StringLeft($fixedFilename, $maxLen)
    EndIf
    Return $fixedFilename
EndFunc  ;==>_NormalizeFilename
Link to comment
Share on other sites

Whoops! Sorry. Trying to clean up the code a bit after posting I broke _DoPaste()

Here's a fixed version.

Func _DoPaste()
    TraySetState(2)
    Local $folder = @ScriptDir & "\PastedScripts\"
    Local $initialFilename = WinGetTitle("[active]")
    Local $fileName = _NormalizeFilename($initialFilename, 32)
    Local $msg = "Paste to filename: " & $fileName & @CRLF & "in folder: " & $folder
    Local $buttonPressed = MsgBox(0x1043, @ScriptName, $msg)
    If $buttonPressed = 2 Then
        TraySetState(1)
        Return
    ElseIf $buttonPressed = 7 Then
        $fileName = InputBox("New AU3 Name", "What would you like to name the file?")
    EndIf
    $file = FileOpen($folder & $fileName & ".au3", 10)
    If $file = -1 Then
        MsgBox(0x1010, @ScriptName, "Unable to open file.")
        TraySetState(1)
        Return
    EndIf
    $fileContents = ClipGet()
    FileWrite($file, $fileContents);Put the contents of the clipboard in the new file
    FileClose($file)
    TraySetState(1)
EndFunc  ;==>_DoPaste
Link to comment
Share on other sites

MilesAhead, thanks for the addition to the script. Or, I guess, reworking of the concept and making a brand new script. Either way I like what you did. I had been brainstorming to try and search the code for some relevant string that I could use to name the created script but your solution is pretty nice, assuming you don't change windows before you activate the hotkey. Good work.

Other People's Stuff:Andy Flesner's AutoIt v3: Your Quick Guide[topic="34302"]Locodarwin's ExcelCom_UDF[/topic][topic="61090"]MrCreatorR's Opera Library[/topic]
Link to comment
Share on other sites

I went through similar decisons with the script in my signature.

I finally opted for creating folders named "Topic#_TopicTitle", then creating files within those folders that are named "Topic#_Post#.au3". Seemed to work decently to allow one to keep track of what-is-what.

edit: correction

Edited by Spiff59
Link to comment
Share on other sites

I went through similar decisons with the script in my signature.

I finally opted for creating folders named "Topic#_TopicTitle", then creating files within those folders that are named "Topic#_Post#.au3". Seemed to work decently to allow one to keep track of what-is-what.

edit: correction

Pretty cool, Spiff. I'm an Opera user instead of IE so unfortunately it doesn't work for me. But I did a test and I liked what it's capable of. You did remind me though that I want to open it automatically in Scite so I appreciate that. 

Edited by muncherw
Other People's Stuff:Andy Flesner's AutoIt v3: Your Quick Guide[topic="34302"]Locodarwin's ExcelCom_UDF[/topic][topic="61090"]MrCreatorR's Opera Library[/topic]
Link to comment
Share on other sites

I made a few more changes. I moved _NormalizeFilename() out into a script of misc functions. The auto copy script now has some of those misc functions interspersed so I'll post the misc function file also. Some of the functions are adaptations or straight use of example code on AutoIt3 Forum. I give attribution where possible.

;
;MilesAheadMisc.au3
;
;misc useful functions for
;inclusion in scripts.
;
;some functions are totatlly original.
;where adapted or used directly I give
;attribution when possible.
;
;MilesAhead
;
#include-once
#include <Array.au3>

;use Scripting.Dictionary object for simple associative arrays
Func _AssocArray()
    Local $aArray = ObjCreate("Scripting.Dictionary")
    If @error Then
        Return SetError(1, 0, 0)
    EndIf
    $aArray.CompareMode = 1
    Return $aArray
EndFunc ;==>_AssocArray

Func _AssocArrayDestroy(ByRef $aArray)
    If Not IsObj($aArray) Then
        Return False
    EndIf
    $aArray.RemoveAll()
    $aArray = 0
    Return True
EndFunc ;==>_AssocArrayDestroy

;filter out empty array strings ("")
Func _ArrayDelBlanks(ByRef $someArray)
    Local $index = -1
    While UBound($someArray) > 0
        $index = _ArraySearch($someArray, "")
        If $index > -1 Then
            _ArrayDelete($someArray, $index)
        Else
            ExitLoop
        EndIf
    WEnd
EndFunc ;==>_ArrayDelBlanks

;return the Windows version as a number or string
;according to $retAsString param.
;example 6.1 for Windows7, 6 for Vista,
;5.1 for XP etc.. as number, as string the
;minor version will be preserved even if .0
;(Vista returns "6.0" etc.)
;
Func _WinVersion($retAsString = 0)
    Local $dwVersion = DllCall("kernel32.dll", "dword", "GetVersion")
    Local $versionStr = String(BitAND($dwVersion[0], 0x00FF))
    $versionStr &= "." & String(BitShift(BitAND($dwVersion[0], 0xFF00), 8))
    If $retAsString Then Return $versionStr
    Return Number($versionStr)
EndFunc ;==>_WinVersion

; return OS enumeration based on @OSVersion for easier comparisons.
; on failure returns $WIN_UNKNOWN and sets @error to 1
;
Global Enum $WIN_UNKNOWN = -1, $WIN_95, $WIN_98, $WIN_ME, $WIN_NT, $WIN_2000, $WIN_XP, $WIN_2003, _
        $WIN_VISTA, $WIN_2008

Func _OsLevel()
    Switch @OSVersion
        Case "WIN_95"
            Return $WIN_95

        Case "WIN_98"
            Return $WIN_98

        Case "WIN_ME"
            Return $WIN_ME

        Case "WIN_NT"
            Return $WIN_NT

        Case "WIN_2000"
            Return $WIN_2000

        Case "WIN_XP"
            Return $WIN_XP

        Case "WIN_2003"
            Return $WIN_2003

        Case "WIN_VISTA"
            Return $WIN_VISTA

        Case "WIN_2008"
            Return $WIN_2008

        Case Else
            Return SetError(1, 0, $WIN_UNKNOWN)
    EndSwitch
EndFunc ;==>_OsLevel

; Reduce memory usage via EmptyWorkingSet()
; Author wOuter ( mostly ) on AutoIt3 forum
Func _ReduceMemory($i_PID = -1)

    If $i_PID <> -1 Then
        Local $ai_Handle = DllCall("kernel32.dll", 'int', 'OpenProcess', 'int', 0x1f0fff, 'int', False, 'int', $i_PID)
        Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'long', $ai_Handle[0])
        DllCall('kernel32.dll', 'int', 'CloseHandle', 'int', $ai_Handle[0])
    Else
        Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'long', -1)
    EndIf

    Return $ai_Return[0]
EndFunc ;==>_ReduceMemory

;returns non 0 if Glass is enabled on Vista/W7
Func _GlassEnabled()
    If _OsLevel() < $WIN_VISTA Then Return 0
    $retValue = DllCall("dwmapi.dll", "int", "DwmIsCompositionEnabled", "int*", "")
    If @error Then Return 0
    Return $retValue[1]
EndFunc ;==>_GlassEnabled

;if $Str contains a space wrap in double quotes
;
;useful for command line params of files that have
;a space in the file path
;
Func _QuoteStr($Str)
    If StringInStr($Str, " ") Then
        Return '"' & $Str & '"'
    EndIf
    Return $Str
EndFunc ;==>_QuoteStr

;returns False if no media in drive or file/folder doesn't exist
;
;for use with complete paths, not for file named 'x'
;in working dir.  Seems to work ok with network paths
;(\\NAME\folder\filename) as well as those starting with
;a drive letter. The idea is to avoid the long time-out
;if FileExists was used by itself on empty drive etc..
;
Func _ValidPath($path)
;filter out obvious junk
    If StringLen($path) < 2 Then Return False

    Local $sysDrive = StringLeft(@WindowsDir, 2)
    Local $drive = StringLeft($path, 2)
    If $sysDrive = $drive Then
        Return FileExists($path)
    EndIf

    Local $driveType = DriveGetType($drive)
    If @error Then Return False
    Switch $driveType

        Case "Unknown"
            Return False

        Case "Network"
            If DriveStatus($drive) = "Invalid" Then Return False

        Case "CDROM", "Removable"
            If DriveStatus($drive) = "NotReady" Then Return False

    EndSwitch

    Return FileExists($path)
EndFunc ;==>_ValidPath

;filter out percent signs, spaces, and illegal filename chars
;and substitute underscores. Optionally chop off return str
;at $maxLen chars.
;
;
Func _NormalizeFilename($inFilename, $maxLen = 0)
    Local Const $illegalFilenameChars = "?[]/\=+<>:;"",* %"
    Local $c = ""
    Local $fixedFilename = ""

    For $x = 1 To StringLen($inFilename)
        $c = StringMid($inFilename, $x, 1)
        If StringInStr($illegalFilenameChars, $c) Then
            $c = "_"
        EndIf
        $fixedFilename &= $c
    Next
    If $maxLen Then
        Return StringLeft($fixedFilename, $maxLen)
    EndIf
    Return $fixedFilename
EndFunc ;==>_NormalizeFilename

;return @ScriptName without extension
;useful for MsgBox titles or path
;building
;
Func _ScriptBaseName()
    Return StringLeft(@ScriptName, (StringInStr(@ScriptName, ".") - 1))
EndFunc ;==>_ScriptBaseName

;a one-liner but saves thinking about it :)
;
Func _ScriptIniFileName()
    Return @ScriptDir & "\" & _ScriptBaseName() & ".ini"
EndFunc ;==>_ScriptIniFileName

;show an error msg and optionally quit, with optional timeout
Func _ShowError($errorMsg, $title = "", $quit = True, $timeOut = 0)
    If $title = "" Then $title = _ScriptBaseName()
    MsgBox(0x1010, $title, $errorMsg, $timeOut)
    If $quit Then Exit
EndFunc ;==>_ShowError

;show usage msg and optionally quit with optional timeout
Func _ShowUsage($usageMsg, $title = "", $quit = True, $timeOut = 0)
    If $title = "" Then $title = _ScriptBaseName()
    MsgBox(0x1040, $title, $usageMsg, $timeOut)
    If $quit Then Exit
EndFunc ;==>_ShowUsage

; Get the execuatble path of a window
; Author gafrost on AutoIt3 forum
Func _WinGetPath($title = "", $strComputer = 'localhost')
    $win = WinGetTitle($title)
    $pid = WinGetProcess($win)
    $wbemFlagReturnImmediately = 0x10
    $wbemFlagForwardOnly = 0x20
    $colItems = ""
    $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
    $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId = " & $pid, "WQL", _
            $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    If IsObj($colItems) Then
        For $objItem In $colItems
            If $objItem.ExecutablePath Then Return $objItem.ExecutablePath
        Next
    EndIf
EndFunc ;==>_WinGetPath

On the pasting code I changed it a bit so that if no extension is specified .au3

is assumed. This way you can use it to auto copy any source from the web or

whatnot by specifying the extension in the input line. I also added a few things

like preventing multiple instances from running, and storing the hotkey in an

.ini file. Change hotkey by editing .ini file.

#Region;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=A.ico
#AutoIt3Wrapper_Outfile=AutoPaste.exe
#EndRegion;**** Directives created by AutoIt3Wrapper_GUI ****
#include <Misc.au3>
#include "MilesAheadMisc.au3"
Const $ERROR_ALREADY_EXISTS = 183
Global $singletonQuit = False

If _Singleton("{33fe229a-8c71-481f-add6-3c47ea3065e0}", 1) = 0 Then
    If @error = $ERROR_ALREADY_EXISTS Then
        $singletonQuit = True
        Exit
    EndIf
EndIf

Opt("TrayMenuMode", 1)
TraySetToolTip(_ScriptBaseName())
$aboutitem = TrayCreateItem("About AutoPaste")
TrayCreateItem("")
$exititem = TrayCreateItem("Quit")
Global $hotKey = ""
_ReadIni()

HotKeySet($hotKey, "_DoPaste")

;sit in tray listening for hotkey
While 1
    $msg = TrayGetMsg()
    Select

        Case $msg = 0
            ContinueLoop

        Case $msg = $aboutitem
            TraySetState(2)
            _About()
            TraySetState(1)

        Case $msg = $exititem
            _Quit()

    EndSelect
WEnd

;adapted from code posted by muncherw on AutoIt3 Forum
; http://www.autoitscript.com/forum/index.php?showtopic=96816
;
Func _DoPaste()
    TraySetState(2)
    HotKeySet($hotKey)
    Local $folder = @ScriptDir & "\PastedScripts\"
    Local $initialFilename = WinGetTitle("[active]")
    Local $fileName = _NormalizeFilename($initialFilename, 32)
    Local $msg = "Paste to filename: " & $fileName & @CRLF & "in folder: " & $folder
    Local $buttonPressed = MsgBox(0x1043, @ScriptName, $msg)
    If $buttonPressed = 2 Then
        HotKeySet($hotKey, "_DoPaste")
        TraySetState(1)
        Return
    ElseIf $buttonPressed = 7 Then
        $fileName = InputBox("New AU3 Name", "What would you like to name the file?")
    EndIf
    If @error Then
        HotKeySet($hotKey, "_DoPaste")
        TraySetState(1)
        Return
    EndIf
    If StringInStr(StringRight($fileName, 4), ".") Then
        $fileName = $folder & $fileName
    Else
        $fileName = $folder & $fileName & ".au3"
    EndIf
    $file = FileOpen($fileName, 10)
    If $file = -1 Then
        MsgBox(0x1010, @ScriptName, "Unable to open file.")
        HotKeySet($hotKey, "_DoPaste")
        TraySetState(1)
        Return
    EndIf
    $fileContents = ClipGet()
    FileWrite($file, $fileContents);Put the contents of the clipboard in the new file
    FileClose($file)
    HotKeySet($hotKey, "_DoPaste")
    TraySetState(1)
EndFunc ;==>_DoPaste

Func _About()
    _ShowUsage("AutoPaste AutoIt Source Saver", "", False)
EndFunc ;==>_About

Func _Quit()
    Exit
EndFunc ;==>_Quit

Func _ReadIni()
    Local $iFile = _ScriptIniFileName()
    $hotKey = IniRead($iFile, "Settings", "HotKey", "+{PgUp}")
EndFunc ;==>_ReadIni

Func _WriteIni()
    Local $iFile = _ScriptIniFileName()
    IniWrite($iFile, "Settings", "HotKey", $hotKey)
EndFunc ;==>_WriteIni

Func OnAutoItExit()
    If Not $singletonQuit Then
        _WriteIni()
    EndIf
EndFunc ;==>OnAutoItExit
Edited by MilesAhead
Link to comment
Share on other sites

After I see the result though, I see why the OP didn't bother. :D Now and then you get a good browser title suitable for a filename, but not often. Still, it's a good way to grab selected text in a semi-organized way. :D

I like the idea, but execution seems tough- you have to hope that whoever posted code gave the post a nice clean name.

Other People's Stuff:Andy Flesner's AutoIt v3: Your Quick Guide[topic="34302"]Locodarwin's ExcelCom_UDF[/topic][topic="61090"]MrCreatorR's Opera Library[/topic]
Link to comment
Share on other sites

I like the idea, but execution seems tough- you have to hope that whoever posted code gave the post a nice clean name.

Hmmmmm, I'm thinking the flaw in how I have it set up is presenting the "normalized filename" on a take it or leave it basis. What I should do is just paste it into the input box. Then the user can change it a bit or just use a different name entirely without the Yes No Cancel crap.

I think this is simpler and closer to the original concept

;adapted from code posted by muncherw on AutoIt3 Forum
; http://www.autoitscript.com/forum/index.php?showtopic=96816
;
Func _DoPaste()
    TraySetState(2)
    HotKeySet($hotKey)
    Local $folder = @ScriptDir & "\PastedScripts\"
    Local $initialFilename = WinGetTitle("[active]")
    Local $prompt = "What would you like to name the file?" & @CRLF & @CRLF & "(.au3 extension added if none specified)"
    Local $fileName = _NormalizeFilename($initialFilename, 32)
    $fileName = InputBox("New Source Filename", $prompt, $fileName)
    If @error Then
        HotKeySet($hotKey, "_DoPaste")
        TraySetState(1)
        Return
    EndIf
    If StringInStr(StringRight($fileName, 4), ".") Then
        $fileName = $folder & $fileName
    Else
        $fileName = $folder & $fileName & ".au3"
    EndIf
    $file = FileOpen($fileName, 10)
    If $file = -1 Then
        MsgBox(0x1010, @ScriptName, "Unable to open file.")
        HotKeySet($hotKey, "_DoPaste")
        TraySetState(1)
        Return
    EndIf
    $fileContents = ClipGet()
    FileWrite($file, $fileContents);Put the contents of the clipboard in the new file
    FileClose($file)
    HotKeySet($hotKey, "_DoPaste")
    TraySetState(1)
EndFunc  ;==>_DoPaste

Now the only thing would be a readme or detailed about box with usage info.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...