Jump to content

SciTE - edge strings with paired chars


BugFix
 Share

Recommended Posts

Hi,

i've made a LUA-script to use in SciTE for more comfort.

Edge selected text with paired chars or set an empty pair on hit this char.

Paired chars are: " ", ' ', ( ), { }, [ ]

* Set edging always in multiple selected lines or in block selected areas (i.e. from line 3 to 8 in columns 20 to 30).

* If caret position are left from selection hit the opening char, on position at the end hit the closing char.

* It also works without selection, so you got empty pairs. The opening char must hit! (like AutoCloseBraces.lua). Hit closing char without selection inserts only this char.

* ! If you want to set empty pairs on multiple lines, you must select 0 columns (hit SHIFT+ALT + n-times DOWN) and the closing char must hit. Downward selection is required for this.

NOTE:

* If you always use an script like 'AutoCloseBraces.lua', you must disable it.

* The paired mode is disabled on using OVERWRITE in editor.

* Keycodes for english and german keyboard layout implemented. Set your language in variable 'lang'. For other languages add own entries in table 'tCode'. To get right values uncomment the 'print'-line in function 'HitKey', hit the keys with pairing chars and read values from console. All entries('SHIFT', 'RAW', 'CTRL_ALT') must created, to avoid errors.

If somewhere add entries for other languages it would nice to post it here for sharing.

The value for INSERT-key is hardcoded with keycode '45' (hope is the same on all keyboard layouts) :D.

Edit 2011-10-30:

* Add functionality to exclude file-types from this behavior (i.e 'cpp')

To exclude some file-types from this function, needs entry for every file-type that should excluded in 'SciTEUser.properties':

'NoPairs.ext=1' (.ext with lower chars!).

To use this script, copy it in path '..\Scite\LUA\'

Now make a new entry in SciTEStartup.lua : 'LoadLuaFile("EdgingSelection.lua")'. Reload StartUpScript (or restart SciTE to take effect).

If you always use an script like 'AutoCloseBraces.lua', it's required to disable this, because the edging script has this funtion too.

Your SciTEStartup.lua should look like this:

--------------------------------------------------------------------------------
-- SciTE startup script.
--------------------------------------------------------------------------------
-- A table listing all loaded files.
LoadLuaFileList = { }
--------------------------------------------------------------------------------
-- LoadLuaFile(file, directory)
--
-- Helper function for easily loading Lua files.
--
-- Parameters:
--  file - The name of a Lua file to load.
--  directory - If specified, file is looked for in that directory.  By default,
--       this directory is $(SciTEDefaultHome)\Lua.
--------------------------------------------------------------------------------
function LoadLuaFile(file, directory)
    if directory == nil then
        directory = props['SciteDefaultHome'] ..'\\Lua\\'    end
    table.insert(LoadLuaFileList, directory .. file)
    dofile(directory .. file)
end -- LoadLuaFile()
 
-- Load all the Lua files.
LoadLuaFile('Class.lua')    -- Always load first.
LoadLuaFile('Common.lua')   -- Always load second.
LoadLuaFile('AutoItPixmap.lua')
LoadLuaFile('AutoHScroll.lua')
LoadLuaFile('AutoItAutoComplete.lua')
LoadLuaFile('LoadSession.lua')
LoadLuaFile('AutoItIndentFix.lua')
LoadLuaFile('EdgeMode.lua')
LoadLuaFile('SmartAutoCompleteHide.lua')
LoadLuaFile('Tools.lua')
LoadLuaFile('AutoItTools.lua')
LoadLuaFile('AutoItGotoDefinition.lua')
--~ LoadLuaFile('AutoCloseBraces.lua')  -- don't use together with 'EdgingSelection.lua'
 
-- Start up the events (Calls OnStartup()).
EventClass:BeginEvents()
 
-- Files are using EventClass must load after Events startup
LoadLuaFile('AutoStampSaveVersion.lua')  -- use Event: 'OnBeforeSave'
LoadLuaFile('MyDebug.lua')
LoadLuaFile('EdgingSelection.lua')     -- use Event: 'OnKey'

And here the LUA script 'EdgingSelection.lua':

(Current version v 1.4)

-- TIME_STAMP   2011-10-30 08:36:30   v 1.4
 
----------------- EdgingSelection.LUA ----------------------------------
--  Edge selected text with paired chars or set an empty pair        --
--  on hit this char.                                                --
--  Paired chars are: " ", ' ', ( ), { }, [ ]                        --
--  * Set edging always in multiple selected lines or in block      --
--  selected areas (i.e. from line 3 to 8 in columns 20 to 30).  --
--  * If caret position are left from selection hit the opening    --
--  char, on position at the end hit the closing char.            --
--  * It also works without selection, so you got empty pairs. The  --
--  opening char must hit! (like AutoCloseBraces.lua)              --
--  Hit closing char without selection inserts only this char.    --
--  * ! If you want to set empty pairs on multiple lines, you must  --
--  select 0 columns (hit SHIFT+ALT + n-times DOWN) and the      --
--  closing char must hit. Downward selection is required for this. --
--  NOTE:                                                            --
--  * If you always use an script like 'AutoCloseBraces.lua', you    --
--  must disable it.                                                --
--  * The paired mode is disabled on using OVERWRITE in editor.    --
--  * Keycodes for english and german keyboard layout implemented.  --
--  Set your language in variable 'lang'. For other languages add   --
--  own entries in table 'tCode'. To get right values uncomment the --
--    'print'-line in function 'HitKey', hit the keys with pairing  --
--  chars and read values from console. All entries('SHIFT', 'RAW', --
--  'CTRL_ALT') must created, to avoid errors.                    --
--  * To exclude some file-types from this function, needs entry for  --
--  every file-typ that should excluded in 'SciTEUser.properties'   --
--    'NoPairs.ext=1' (.ext with lower chars!).                    --
------------------------------------------------------------------------
 
----------------- create new EventClass, event: OnKey ------------------
HitKey = EventClass:new(Common)
------------------------------------------------------------------------
 
----------------- declare vars -----------------------------------------
-- set your language and add table with values
local lang = 'GE' -- 'EN'                                                                  -- language identifier, used in char-table
 
-- virtual keycode
local tCode = {}
 
-- german keyboard
tCode['GE'] = {}
tCode['GE']['SHIFT'] = { [50] = '"', [191] = "'", [56] = '(', [57] = ')' }                -- chars on hit SHIFT (german)
tCode['GE']['CTRL_ALT'] = { [55] = '{', [56] = '[', [57] = ']', [48] = '}' }                -- chars on hit CTRL+ALT (german)
tCode['GE']['RAW'] = {}                                                                  -- empty table required to avoid errors
 
-- US/ english keyboard
tCode['EN'] = {}
tCode['EN']['SHIFT'] = { [48] = ')', [57] = '(', [219] = '{', [221] = '}', [222] = '"' }    -- chars on hit SHIFT (english)
tCode['EN']['CTRL_ALT'] = {}                                                                -- empty table required to avoid errors
tCode['EN']['RAW'] = { [219] = '[', [221] = ']', [222] = "'" }                            -- chars hit alone (english)
 
-- paired chars
local tPairs = {}
tPairs['Left']  = { ['('] = ')', ['{'] = '}', ['['] = ']', ['"'] = '"', ["'"] = "'" }      -- left/opening chars
tPairs['Right'] = { [')'] = '(', ['}'] = '{', [']'] = '[', ['"'] = '"', ["'"] = "'" }      -- right/closing chars
 
-- insert key state
local stateINS = 0
------------------------------------------------------------------------
 
------------------ get pairs -------------------------------------------
function sibling(_sChar)
    local leftChar, rightChar
    if tPairs['Left'][_sChar] ~= nil then
        rightChar = tPairs['Left'][_sChar]
        leftChar = tPairs['Right'][rightChar]
    elseif  tPairs['Right'][_sChar] ~= nil then
        leftChar = tPairs['Right'][_sChar]
        rightChar = tPairs['Left'][leftChar]
    end
    return leftChar, rightChar
end  --> sibling
------------------------------------------------------------------------
 
----------------- set edging -------------------------------------------
function EdgeSelection(_hitChar)
    local leftChar, rightChar = sibling(_hitChar)
    local selStart  = editor.SelectionStart
    local selEnd    = editor.SelectionEnd
    local firstLine = editor:LineFromPosition(selStart)
    local lastLine  = editor:LineFromPosition(selEnd)
    local sSelection aPos = {} n = 0
    local caret, sSelection, fLeft
    caret = editor.CurrentPos
    if caret <= selStart then fLeft = 1 else fLeft = 0 end -- is caret left from selection?
    if (selStart == selEnd) and (tPairs['Right'][_hitChar] ~= nil) and (_hitChar ~= "'" and _hitChar ~= '"') then return nil end
    -- store selected area (start- /endposition in used lines)
    -- from 2nd line add to position the count of chars to insert
    for i = firstLine, lastLine do
        aPos[i] = {}
        aPos[i][1] = editor:GetLineSelStartPosition(i) + n*2
        aPos[i][2] = editor:GetLineSelEndPosition(i) + n*2
        n = n +1
    end
    -- insert edging chars at start- /endposition
    editor:BeginUndoAction()
    if firstLine == lastLine then
        if fLeft == 1 then editor:InsertText(aPos[firstLine][2], rightChar) end
        if fLeft == 0 then editor:InsertText(aPos[firstLine][1], leftChar) editor:GotoPos(caret +1) end
    else
        n = 0
        for i = firstLine, lastLine do
            if fLeft == 1 and i == firstLine then
                editor:InsertText(aPos[i][2], rightChar)
            elseif fLeft == 0 and i == lastLine then
                editor:InsertText(aPos[i][1], leftChar) editor:GotoPos(caret +n*2 +1)
            else
                if fLeft == 1 and n > 0 then aPos[i][1] = aPos[i][1] -1 aPos[i][2] = aPos[i][2] -1 end
                editor:InsertText(aPos[i][2], rightChar)
                editor:InsertText(aPos[i][1], leftChar)
            end
            n = n +1
        end
    end
    editor:EndUndoAction()
end  --> EdgeSelection
------------------------------------------------------------------------
 
----------------- Event: OnKey -----------------------------------------
function HitKey:OnKey(_keycode, _shift, _ctrl, _alt)
--~ print('_keycode: '..tostring(_keycode)..', _shift: '..tostring(_shift)..', _ctrl: '..tostring(_ctrl)..', _alt: '..tostring(_alt))  -- DebugToConsole
    if tonumber(props['NoPairs.'..props['FileExt']:lower()]) == 1 then return nil end   -- to exclude file-types from this function
    if _keycode == 45 then if stateINS == 0 then stateINS = 1 else stateINS = 0 end end  -- on hit INSERT-key change key-state
    if stateIns == 1 then return nil end                                                 -- INSERT-key in OVERWRITE-mode
    if tCode[lang]['SHIFT'][_keycode] ~= nil and _shift == true then return EdgeSelection(tCode[lang]['SHIFT'][_keycode]) end
    if tCode[lang]['CTRL_ALT'][_keycode] ~= nil and _ctrl == true and _alt == true then return EdgeSelection(tCode[lang]['CTRL_ALT'][_keycode]) end
    if tCode[lang]['RAW'][_keycode] ~= nil then return EdgeSelection(tCode[lang]['RAW'][_keycode]) end
    return nil
end  --> HitKey
------------------------------------------------------------------------

Some pictures, how to use:

- selection 0-columns, n-lines (SHIFT+ALT+ n-times DOWN)

Posted Image

- than hit closing char

Posted Image

- block selection

Posted Image

- quote as string in every line on hit one time: "

Posted Image

- select list of variables

Posted Image

- cursor is left, hit opening brace

Posted Image

(pooh, full editor has crashed all the text, i hope i've all correct restored)

EdgingSelection1.4.lua.zip

Edited by BugFix

Best Regards BugFix  

Link to comment
Share on other sites

Sorry for double Post, but i can't change my attechement, was the wrong file-version ( disable on Overwrite-mode not implemented ).

Don't see button 'Full Editor'. :D

Edited by BugFix

Best Regards BugFix  

Link to comment
Share on other sites

Looks like a good idea bugfix.

In your example shiwn in post #1 there is an error - I think you would need

- quote as string in every line on hit one time: "

to have the semi colons outside of the quotes.

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

to have the semi colons outside of the quotes.

Thanks for reply.

The example shows edging of selected areas, if you don't wan't to do this with semicolons -- don't select them.

Edited by BugFix

Best Regards BugFix  

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...