<commit_before>/*
 * DBeaver - Universal Database Manager
 * Copyright (C) 2010-2019 <NAME> (<EMAIL>)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jkiss.dbeaver.ui.editors.sql.util;

import org.eclipse.jface.text.*;
import org.eclipse.jface.text.link.*;
import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags;
import org.eclipse.jface.text.link.LinkedModeUI.IExitPolicy;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditorBase;
import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLPartitionScanner;
import org.jkiss.dbeaver.ui.editors.sql.templates.SQLTemplatesPage;

import java.util.ArrayList;
import java.util.List;

public class SQLSymbolInserter implements VerifyKeyListener, ILinkedModeListener {

    static protected final Log log = Log.getLog(SQLSymbolInserter.class);

    private boolean closeSingleQuotes = true;
    private boolean closeDoubleQuotes = true;
    private boolean closeBrackets = true;

    private final String CATEGORY = toString();
    private IPositionUpdater positionUpdater = new ExclusivePositionUpdater(CATEGORY);
    private List<SymbolLevel> bracketLevelStack = new ArrayList<>();
    private SQLEditorBase editor;
    private ISourceViewer sourceViewer;

    public SQLSymbolInserter(SQLEditorBase editor)
    {
        this.editor = editor;
        this.sourceViewer = editor.getViewer();
    }

    public void setCloseSingleQuotesEnabled(boolean enabled)
    {
        closeSingleQuotes = enabled;
    }

    public void setCloseDoubleQuotesEnabled(boolean enabled)
    {
        closeDoubleQuotes = enabled;
    }

    public void setCloseBracketsEnabled(boolean enabled)
    {
        closeBrackets = enabled;
    }

    private boolean hasIdentifierToTheRight(IDocument document, int offset)
    {
        try {
            int end = offset;
            IRegion endLine = document.getLineInformationOfOffset(end);
            int maxEnd = endLine.getOffset() + endLine.getLength();
            while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
                ++end;

            return end != maxEnd && Character.isJavaIdentifierPart(document.getChar(end));

        }
        catch (BadLocationException e) {
            // be conservative
            log.debug(e);
            return true;
        }
    }

    private boolean hasIdentifierToTheLeft(IDocument document, int offset)
    {
        try {
            IRegion startLine = document.getLineInformationOfOffset(offset);
            int minStart = startLine.getOffset();
            return offset != minStart && Character.isJavaIdentifierPart(document.getChar(offset - 1));

        }
        catch (BadLocationException e) {
            log.debug(e);
            return true;
        }
    }

    private boolean hasCharacterToTheRight(IDocument document, int offset, char character)
    {
        try {
            int end = offset;
            IRegion endLine = document.getLineInformationOfOffset(end);
            int maxEnd = endLine.getOffset() + endLine.getLength();
            while (end != maxEnd && Character.isWhitespace(document.getChar(end))) {
                ++end;
            }

            return end != maxEnd && document.getChar(end) == character;

        }
        catch (BadLocationException e) {
            log.debug(e);
            // be conservative
            return true;
        }
    }

    @Override
    public void verifyKey(VerifyEvent event)
    {

        if (!event.doit) {
            return;
        }
        if (editor.isBlockSelectionModeEnabled()) {
            return;
        }

        IDocument document = sourceViewer.getDocument();

        final Point selection = sourceViewer.getSelectedRange();
        final int offset = selection.x;
        final int length = selection.y;

        switch (event.character) {
            case '(':
            case '[':
                if (!closeBrackets) {
                    return;
                }
                if (hasCharacterToTheRight(document, offset + length, event.character)) {
                    return;
                }

                // fall through

            case '\'':
                if (event.character == '\'') {
                    if (!closeSingleQuotes) {
                        return;
                    }
                    if (hasIdentifierToTheLeft(document, offset)
                        || hasIdentifierToTheRight(document, offset + length)) {
                        return;
                    }
                }

                // fall through

            case '"':
                if (event.character == '"') {
                    if (!closeDoubleQuotes) {
                        return;
                    }<commit_msg>#5232 SQL Editor: bracket auto-close strategy fix<commit_after>/*
 * DBeaver - Universal Database Manager
 * Copyright (C) 2010-2019 <NAME> (<EMAIL>)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jkiss.dbeaver.ui.editors.sql.util;

import org.eclipse.jface.text.*;
import org.eclipse.jface.text.link.*;
import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags;
import org.eclipse.jface.text.link.LinkedModeUI.IExitPolicy;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditorBase;
import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLPartitionScanner;
import org.jkiss.dbeaver.ui.editors.sql.templates.SQLTemplatesPage;

import java.util.ArrayList;
import java.util.List;

public class SQLSymbolInserter implements VerifyKeyListener, ILinkedModeListener {

    static protected final Log log = Log.getLog(SQLSymbolInserter.class);

    private boolean closeSingleQuotes = true;
    private boolean closeDoubleQuotes = true;
    private boolean closeBrackets = true;

    private final String CATEGORY = toString();
    private IPositionUpdater positionUpdater = new ExclusivePositionUpdater(CATEGORY);
    private List<SymbolLevel> bracketLevelStack = new ArrayList<>();
    private SQLEditorBase editor;
    private ISourceViewer sourceViewer;

    public SQLSymbolInserter(SQLEditorBase editor)
    {
        this.editor = editor;
        this.sourceViewer = editor.getViewer();
    }

    public void setCloseSingleQuotesEnabled(boolean enabled)
    {
        closeSingleQuotes = enabled;
    }

    public void setCloseDoubleQuotesEnabled(boolean enabled)
    {
        closeDoubleQuotes = enabled;
    }

    public void setCloseBracketsEnabled(boolean enabled)
    {
        closeBrackets = enabled;
    }

    private boolean hasIdentifierToTheRight(IDocument document, int offset)
    {
        try {
            int end = offset;
            IRegion endLine = document.getLineInformationOfOffset(end);
            int maxEnd = endLine.getOffset() + endLine.getLength();
            while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
                ++end;

            return end != maxEnd && Character.isJavaIdentifierPart(document.getChar(end));

        }
        catch (BadLocationException e) {
            // be conservative
            log.debug(e);
            return true;
        }
    }

    private boolean hasIdentifierToTheLeft(IDocument document, int offset)
    {
        try {
            IRegion startLine = document.getLineInformationOfOffset(offset);
            int minStart = startLine.getOffset();
            return offset != minStart && Character.isJavaIdentifierPart(document.getChar(offset - 1));

        }
        catch (BadLocationException e) {
            log.debug(e);
            return true;
        }
    }

    private boolean hasCharacterToTheRight(IDocument document, int offset, char character)
    {
        try {
            int end = offset;
            IRegion endLine = document.getLineInformationOfOffset(end);
            int maxEnd = endLine.getOffset() + endLine.getLength();
            while (end != maxEnd && Character.isWhitespace(document.getChar(end))) {
                ++end;
            }

            return end != maxEnd && document.getChar(end) == character;

        }
        catch (BadLocationException e) {
            log.debug(e);
            // be conservative
            return true;
        }
    }

    @Override
    public void verifyKey(VerifyEvent event)
    {

        if (!event.doit) {
            return;
        }
        if (editor.isBlockSelectionModeEnabled()) {
            return;
        }

        IDocument document = sourceViewer.getDocument();

        final Point selection = sourceViewer.getSelectedRange();
        final int offset = selection.x;
        final int length = selection.y;

        switch (event.character) {
            case '(':
            case '[':
                if (!closeBrackets) {
                    return;
                }
                try {
                    if (offset < document.getLength() && !Character.isWhitespace(document.getChar(offset + length))) {
                        return;
                    }
                } catch (BadLocationException e) {
                    log.debug(e);
                    return;
                }
/*
                if (hasCharacterToTheRight(document, offset + length, event.character)) {
                    return;
                }
*/

                // fall through

            case '\'':
                if (event.character == '\'') {
                    if (!closeSingleQuotes) {
                        return;
                    }
                    if (hasIdentifierToTheLeft(document, offset)
                        || hasIdentifierToTheRight(document, offset + length)) {
                        return;
                    }
                }

                // fall through

            case '"':
                if (event.character == '"') {
                    if (!closeDoubleQuotes) {
                        return;
                    }
{'fraction_non_alphanumeric': 0.0913527397260274, 'fraction_numerical': 0.0025684931506849314, 'mean_word_length': 2.115764203787677, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3322159', 'n_tokens_mistral': 3166, 'n_tokens_neox': 3047, 'n_words': 732}