Click here to Skip to main content
15,867,330 members
Articles / Programming Languages / XML

Creating AutoComplete HTML Tags in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
1 May 2016CPOL3 min read 14.7K   347   11   1
In this article we will automatically close the HTML tags when starting tag is typed in RichTextBox in C#
Download Source Code


Image 1

Introduction

Nowdays,almost in all advanced HTML,PHP,JavaScript,Perl etc. editors support automatically closing HTML tags feature.
Visual Studio provides rich built feature like automatically closing tags with AutoCompletion(Code Completion).
In this article, we will create automatically completing the HTML tags.
Download the source code to view simple and advanced HTML tags completion.

Procedure

Step 1 : Create Windows Forms Application in C#.
Step 2 : Drag & Drop RichTextBox onto that Form.
Step 3 : Add KeyPress & KeyDown events to RichTextBox.

Using the code

First declare the variables :

C#
public static String EnteredString = "";
public static Boolean Is_LessThanKeyPressed = false;
public static Boolean Is_GreaterThanKeyPressed = false;
public static Boolean Is_AutoCompleteCharacterPressed = false;
public Boolean Is_SpaceBarKeyPressed = false;
public Boolean Is_TagClosedKeyPressed = false;

 

EnteredString : String variable to hold typed characters in RichTextBox.        
Is_LessThanKeyPressed : The value is set to true when "<" key is pressed,because HTML tag starts with "<"(e.g.: <html )
Is_GreaterThanKeyPressed : The value is set to true when ">" key is pressed,when ">" key is pressed,
                        i)  Select the current index from RichTextBox.
                        ii) Insert proper closing tags associated with starting tag at current index position.
Is_AutoCompleteCharacterPressed : The value is set to true when auto complete character is pressed like( ",',[,( ) for performing AutoCompleteBrackets feature.
Is_SpaceBarKeyPressed : The value is set to true when Space key is down.This variable is used to complete html tags even if space bar key is pressed.We press the space bar key to add attributes to given html tag,so to complete this tag,we need this variable.
Is_TagClosedKeyPressed : The value is set to true when html tag is completed by user not automatically or when auto completion feature fails then user must end the tag,when he ends then tag by pressing ">" key then that tag must not be completed again.                        

               
Declare the array list of html tags :

C#
public String[] tagslist ={
    "html",
    "head",
    "title",
    "body",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "b",
    "u",
    "i",
    "sub",
    "sup",
    "center",
    "strike",
    "font",
    "p",
    "style",
    "pre",
    "a",
    "img",
    "table",
    "tr",
    "th",
    "td",
    "form",
    "input",
    "div",
    };

 

KeyPress event : Get the pressed character.If it is "<" then set EnteredString="", Is_LessThanKeyPressed value to true and Is_SpaceBarKeyPressed value to false.
If pressed character is ">" then first check Is_TagClosedKeyPressed value is false or not, if it is false then set Is_GreaterThanKeyPressed value to true & Is_SpaceBarKeyPressed value to false and insert the closing tag at 
current SelectionStart position in RichTextBox by matching EnteredString with each element in tagslist.
Once tag is inserted then set EnteredString="".
If pressed key is other character then first check if it is letter or digit,if it is then concat that character with 
EnteredString.
Here's the code

C#
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    String ch = e.KeyChar.ToString();


    this.ProcessAutoCompleteBrackets(ch);

    if (ch == "<")
    {
        Is_LessThanKeyPressed = true;
        Is_SpaceBarKeyPressed = false;
        EnteredString = "";
    }
    else if (ch == ">")
    {
        if (!Is_TagClosedKeyPressed)
        {
            Is_GreaterThanKeyPressed = true;
            Is_SpaceBarKeyPressed = false;

            int oldsel = richTextBox1.SelectionStart;

            for (int i = 0; i < tagslist.Length; i++)
            {
                if (EnteredString == tagslist[i])
                {
                    richTextBox1.Text = richTextBox1.Text.Insert(oldsel, "<!--" + tagslist[i] + "-->");
                    richTextBox1.SelectionStart = richTextBox1.SelectionStart + oldsel;
                    EnteredString = "";
                }
            }

            Is_LessThanKeyPressed = false;
        }
        else
        {
            Is_TagClosedKeyPressed = false;
        }
    }

    else
    {
        if (Is_LessThanKeyPressed)
        {
            for (char a = 'a'; a <= 'z'; a++)
            {
                if (a.ToString() == ch)
                {
                    EnteredString += ch;
                }
                else if (a.ToString().ToUpper() == ch)
                {
                    EnteredString += ch;
                }
            }
            for (int a = 0; a <= 9; a++)
            {
                if (a.ToString() == ch)
                {
                    EnteredString += ch;
                }
            }
        }
    }


    // if user itself closes the tag
    if (Is_LessThanKeyPressed)
    {
        if (ch == "/")
        {
            Is_TagClosedKeyPressed = true;
            Is_SpaceBarKeyPressed = true;
            EnteredString = "";
        }
    }
}

 

KeyDown event : If key is Space then set the value of EnteredString to the same value of exists in tagslist.
If key is Up,Down,Left,Right then first check Is_AutoCompleteCharacterPressed is false,if it is then set 
EnteredString="" & Is_AutoCompleteCharacterPressed = false & Is_SpaceBarKeyPressed=false.
If key is Back then get the character from current position.if that character is not equal to ">" then remove that character from RichTextBox,if that character is "<" then set EnteredString="".

C#
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Space:
            Is_SpaceBarKeyPressed = true;

            if (Is_GreaterThanKeyPressed)
            {
                Is_GreaterThanKeyPressed = false;
            }
            Is_LessThanKeyPressed = false;

            for (int i = 0; i < tagslist.Length; i++)
            {
                if(EnteredString==tagslist[i])
                {
                    EnteredString = tagslist[i];
                }
            }
            break;

        case Keys.Up:
            if (Is_AutoCompleteCharacterPressed == false)
            {
                EnteredString = "";
                Is_AutoCompleteCharacterPressed = false;
            }
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Down:
            if (Is_AutoCompleteCharacterPressed == false)
            {
                EnteredString = "";
                Is_AutoCompleteCharacterPressed = false;
            }
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Left:
            if (Is_AutoCompleteCharacterPressed == false)
            {
                EnteredString = "";
                Is_AutoCompleteCharacterPressed = false;
            }
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Right:
            if (Is_AutoCompleteCharacterPressed == false)
            {
                EnteredString = "";
                Is_AutoCompleteCharacterPressed = false;
            }
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Enter: EnteredString = "";
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Back:
            int sel = richTextBox1.SelectionStart;
            Point pt = richTextBox1.GetPositionFromCharIndex(sel);
            char ch = richTextBox1.GetCharFromPosition(pt);
            if (EnteredString.Length > 0)
            {
                if (ch != '>')
                {
                    EnteredString = EnteredString.Remove(EnteredString.Length - 1);
                    Is_LessThanKeyPressed = true;
                }
            }
            if (ch == '<')
            {
                EnteredString = "";
            }
            break;
    }
}

 

With AutoCompletion Feature

Image 2

We will also create AutoComplete HTML tags with AutoCompletion(Code Completion) feature.
Dont know how to create AutoCompletion in C#,

         Creating Auto Completion/Code Completion in C#

Coding is same as defined in above article link,only just adding AutoComplete HTML tags feature and modifying contents.
Download the source code to view automatic html tags completion with autocompletion feature.
With autocompletion feature you can direcly select tags from the popped up list and can complete them by just pressing ">" key on it.
I have created ACHTMLTags.cs(AutoCompleteHTMLTags) class in source code.   

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Software Engineer

Comments and Discussions

 
QuestionRequest to edit and use this control for a OpenSource Text Editor I am creating with LineNumbers Pin
Member 140860425-Feb-21 10:08
Member 140860425-Feb-21 10:08 
Hello,

I wanted to request permission to use your ACHTMLTag control in a open source project I am working on. I Have quite a few edits and stuff to it for it to work with my project but first wanted to be sure I could use it. As well as what kind of attribution you would like?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.