image thumbnail

extend Matlab Editors callback

by

 

03 Apr 2013 (Updated )

Extends the editor features. Closing brackets, Operator. Templates, Keyboard Shortcuts

Matlab_extendEditorFunctionality.m
function Matlab_extendEditorFunctionality(activateFlg,mFileName)
% One-line description here, please.
%
% INVOKING: outputpara = Matlab_extendEditorFunctionality(inputpara)
%
% CATEGORY: Aid  D:\sds\tools\DA\MatlabM\Tools
%
%% DESCRIPTION
%   
%
%% INPUT
%     activateFlg ... (true|{false})-(set|{reset}) Keytypedcallback
%
%% OUTPUT
%    outputpara ... 
%
%% EXAMPLES
%{

a = matlab.desktop.editor.EditorUtils.getJavaEditorApplication
b = a.getActiveEditor.getComponent.getComponent(0).getComponent(0).getComponent(0).getComponent(0).getComponent(1).getComponent(0).getComponent(0)
uiinspect(b)

cb = handle(b,'CallbackProperties')
set(cb,'KeyTypedCallback',@(src, evnt) disp(evnt.toString))
set(cb,'KeyTypedCallback',@(src, evnt) disp(src.toString)))

%}  
%% VERSIONING
%             Author: Andreas Justin
%           Copyright 
%      Creation date: 2013-03-22
%             Matlab: 8.0.0.783 (R2012b)
%  Required Products: -
%
%% REVISIONS
%
% V1.0 | 2013-03-22 |    Andreas Justin | Ersterstellung
% V1.1 | 2013-03-24 |    Andreas Justin | Automatische ertstellung eines Kommentar blocks
% V1.2 | 2013-09-05 |    Andreas Justin | operatoren +=, -=, \=, *= hinzugefgt incl. autovervollfstndigung
% V1.3 | 2013-09-23 |    Andreas Justin | R2013b support
% V1.4 | 2013-09-24 |    Andreas Justin | Breakpointbar wird colorisiert wenn edit aktiv ist
%
% See also 

%#ok<*NASGU>
%#ok<*AGROW>
%% --------------------------------------------------------------------------------------------
if nargin < 1 || isempty(activateFlg)
    activateFlg = false;
end
if nargin < 2;  mFileName = ''; end
% KeyTypedCallback           characters - no Function Keys, only one which won't interfere with matlab tab complete
% KeyPressedCallback         at Press
% KeyReleasedCallback        at release
%% --------------------------------------------------------------------------------------------
colorOff = [0.94118,0.94118,0.94118,1];
colorOn =  [179,203,111,255]./255;
jMainPane = [];
jEditor = com.mathworks.mde.desk.MLDesktop.getInstance.getGroupContainer('Editor');
if ~isempty(jEditor)
    for childIdx = 1 : jEditor.getComponentCount
        componentClassName = regexprep(jEditor.getComponent(childIdx-1).class,'.*\.','');
        if any(strcmp(componentClassName,{'DTMaximizedPane','DTFloatingPane','DTTiledPane'}))
            jMainPane = jEditor.getComponent(childIdx-1);
            break;
        end
    end
else
    return
end
if isa(jMainPane,'com.mathworks.mwswing.desk.DTFloatingPane')
    jMainPane = jMainPane.getComponent(0);  % a com.mathworks.mwswing.desk.DTFloatingPane$2 object
end
if verLessThan('matlab','8.2')
    % R2013a und kleiner
    for jj = 1:jMainPane.getComponentCount
        hEditorPane = [];
        
        jSyntaxTextPaneView = getDescendent(jMainPane.getComponent(jj-1),[0,0,1,0,0,0,0]);
        
        if isa(jSyntaxTextPaneView,'com.mathworks.widgets.SyntaxTextPaneMultiView$1')
            % cprintf('Comment','Found\n')
            hEditorPane(1) = handle(getDescendent(jSyntaxTextPaneView.getComponent(1),[1,0,0]),'CallbackProperties');
            hEditorPane(2) = handle(getDescendent(jSyntaxTextPaneView.getComponent(2),[1,0,0]),'CallbackProperties');
        else
            % cprintf('Keywords','Found alternativ\n')
            jEditorPane = getDescendent(jSyntaxTextPaneView,[1,0,0]);
            hEditorPane = handle(jEditorPane,'CallbackProperties');
        end
        hEditorPaneArray(jj) = hEditorPane;
    end
else % matlab R2013b
    a = matlab.desktop.editor.EditorUtils.getJavaEditorApplication;
    mFileName = regexprep(mFileName,'\.m$','','once');
    if ~isempty(regexp(mFileName,':','once'))
       mFileName = regexp(mFileName,'(?<=\\)[^\\]+$','match','once');
    end
    mFileName_ = regexp(mFileName,'(?<=\.)[^\.\\]+$','match','once');
    if ~isempty(mFileName_) % object
        mFileName = mFileName_;
    end
    for jj = 0:a.getOpenEditors.size-1
        mFileNameShort = regexprep(char(a.getOpenEditors.get(jj).getShortName),'\.m$','','once');
        if isempty(mFileName) || strcmpi(mFileName,mFileNameShort) % edit ignores case
            % bei Startup oder bei edit befehl wird fr den "neuen" editor das DaEditor object
            % erzeugt
            if activateFlg
                if ~daEditor.DaEditor.isShortNameInRoot(mFileNameShort)
                    lName = a.getOpenEditors.get(jj).getLongName;
                    dE = daEditor.DaEditor(a.getOpenEditors.get(jj));
                    dE.setKeyReleasedCallback();
                    dE.setMouseReleasedCallback();
                    dE.addToRoot();
                end
            else
                if daEditor.DaEditor.isShortNameInRoot(mFileNameShort)
                    dE = daEditor.DaEditor.getFromRoot(mFileNameShort);
                    dE.releaseFromRoot(0);
                end
            end
            b = a.getOpenEditors.get(jj).getComponent.getComponent(0).getComponent(0).getComponent(0).getComponent(0).getComponent(1).getComponent(0).getComponent(0);
            hEditorPane = handle(b,'CallbackProperties');
            hEditorPaneArray(jj+1) = hEditorPane;
            setCallback(hEditorPane,activateFlg);
        end
    end
end

function child = getDescendent(child,listOfChildrenIdx)
    if ~isempty(listOfChildrenIdx)
        child = getDescendent(child.getComponent(listOfChildrenIdx(1)),listOfChildrenIdx(2:end));
    end
function setCallback(hEditorPane,activateFlg)
    if activateFlg
        set(hEditorPane,'KeyTypedCallback',@(src,evnt)Editor_KeyTypedCallback(src,evnt))
    else
        set(hEditorPane,'KeyTypedCallback','')
    end
%% <Jonathan Sullivan> with minor changes
% http://www.mathworks.co.uk/matlabcentral/fileexchange/authors/120880

function [names, access, component] = findAllComponents(jMainPane,names,access,component,access_base)
    cmps = jMainPane.getComponents;
    if nargin == 1;
        names = {};
        access = {};
        access_base = [];
        component = {};
    end
    for ii = 1:length(cmps)
%         c = regexp(char(cmps(ii).toString),'\.([^\[\.]+)\[','tokens');
        c = regexp(char(cmps(ii).class),'\.([^\[\.]+$)','tokens');
        names{end+1} = c{1}{1};
        access{end+1} = [access_base ii-1];
        component{end+1} = cmps(ii);
        [names, access, component] = findAllComponents(jMainPane.getComponent(ii-1),names,access,component,access{end});
    end
    names = names(:);
    access = access(:);
    component = component(:);
%% <\Jonathan Sullivan>
function putIn = getPutIn(inPut,entireText,cursorPos,offset)
    switch inPut
        case '('
            if ~DA_getUserProfileSetting('EnableAutoBrackets');    putIn = ''; return; end
            putIn = ')';
        case '"'
            if ~DA_getUserProfileSetting('EnableAutoBrackets');    putIn = ''; return; end
            putIn = '"';
        case '['
            if ~DA_getUserProfileSetting('EnableAutoBrackets');    putIn = ''; return; end
            putIn = ']';
        case '{'
            if ~DA_getUserProfileSetting('EnableAutoBrackets');    putIn = ''; return; end
            putIn = '}';
        case ''''
            if ~DA_getUserProfileSetting('EnableAutoBrackets');    putIn = ''; return; end
            putIn = '''';
        case '='
            if ~DA_getUserProfileSetting('EnableOperator');       putIn = ''; return; end
            putIn = '=';
        case '%'
            putIn = '%';
    end
    chk = any(strcmp(entireText(cursorPos-1+offset),{'(','[','{','''','"','=','%'}));
    if ~(numel(entireText) < cursorPos+offset)
        chk = chk && isempty(regexp(entireText(cursorPos+offset),'[a-zA-Z0-9\(\{\[\'''']','match'));     % rechts
    end
    if (cursorPos-2+offset > 0)
        chk = chk && isempty(regexp(entireText(cursorPos-2+offset),'[\.]','match'));  % links
        if strcmp(putIn,'''')
            chk = chk && isempty(regexp(entireText(cursorPos-2+offset),'[a-zA-Z0-9\)\}\]]','match'));
        end
    end
    if ~chk
        putIn = '';
    end
function Editor_KeyTypedCallback(~,evnt, varargin)
    keyChar = get(evnt,'keyChar');
    operExpr = '(+|-|*|/)';
    if strcmp(keyChar,'(') || strcmp(keyChar,'"') || ...
       strcmp(keyChar,'[') || strcmp(keyChar,'''') || ...
       strcmp(keyChar,'{') || strcmp(keyChar,'=') || ...
       strcmp(keyChar,'%')

        aE = matlab.desktop.editor.getActive;
        pos = aE.Selection;
        pos(2,1:4) = pos;
        cursorPos = matlab.desktop.editor.positionInLineToIndex(aE, pos(1,1),pos(1,2));
        putIn = getPutIn(keyChar,aE.Text,cursorPos,0);
        switch putIn
            case {'''',')',']','"'}
                aE.insertTextAtPositionInLine(putIn,pos(1,1),pos(1,2));
                aE.goToPositionInLine(pos(2,1),pos(2,2));
            case '}'
                allSpace = regexp(aE.Text(...
                    matlab.desktop.editor.positionInLineToIndex(aE,pos(1,1),1):cursorPos-3),...
                    '\S','match','once');
                if isempty(allSpace) && cursorPos-2 > 0 && strcmp(aE.Text(cursorPos-2),'%')
                    spaces = blanks(pos(1,2)-3);
                    putIn = [char(13),spaces,'  ',char(13),spaces,'%}'];
                    pos(2,1:2) = pos(2,1:2) + [1,0]; % moves the cursor in the line between the comment block
                end
                
                aE.insertTextAtPositionInLine(putIn,pos(1,1),pos(1,2));
                aE.goToPositionInLine(pos(2,1),pos(2,2));
            case '='
                o = regexp(aE.Text(cursorPos-2),operExpr,'match','once');
                if ~isempty(o)
                    txt = [aE.Text(matlab.desktop.editor.positionInLineToIndex(aE,pos(1,1),1):cursorPos-1)];
                    % [^\s]+?                   !space at least 1 times as much as possible lazy expression
                    % [\s]*?                    can be space but don't has to
                    % (?=(\(|\[|\{|\+|\-|\*|/)) lookahead from previous position and test if any of these are there
                    % [^\+\-\/\*]*              any character but not these as much as possible
                    % (?=\s*(\+|\-|\*|\/))      lookahead from previous position can be space followed by an operator
                    var = regexp(txt,'[^\s]+?[\s]*?(?=(\(|\[|\{|\+|\-|\*|/))[^\+\-\/\*]*(?=\s*(\+|\-|\*|\/))','match','once');
                    
                    txt = regexprep(txt,'^\s+','');
                    txt = regexprep(txt,'([+*()\\/.\[\]])','\\$1');
                    mFileReplaceTextWith(aE,txt,[var,'= ',var,o,' '])
                end
            case '%'
                txt = aE.Text(matlab.desktop.editor.positionInLineToIndex(aE,pos(1,1),1):cursorPos-1);
                action = regexpi(txt,'%(DAComment|DAFunction|[\w\.(),]+)%','match','once');
                
                if ~isempty(action)
                    if strcmpi(action,'%DAComment%') || strcmpi(action,'%DAFunction%')
%                         mFileReplaceTextWith(aE,'','\DoComment')
                    else
                        newText = Matlab_extendEditorFunctionality_StringReplacements(action);
%                         mFileReplaceTextWith(aE,action,newText)
                        dE = daEditor.DaEditor(aE.Filename);
                        dE.regexRep(action,newText,true);
                    end
                end
        end
    end

function filNam = getFileName(evnt)
    filNam = char(evnt.getSource.getFilename);

Contact us