>From 03fcfd46ae1350191d7aad64115933b7fd2c6431 Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horiguchi.kyotaro@lab.ntt.co.jp>
Date: Fri, 30 Oct 2015 18:18:18 +0900
Subject: [PATCH 3/4] Replace existing completions with regular expressions as
 is.

This patch simply replaces each completions with regular
expressoins. No optimization or enhancement is done.
---
 src/bin/psql/Makefile       |    6 +-
 src/bin/psql/tab-complete.c | 2551 +++++++++++++++++++------------------------
 2 files changed, 1109 insertions(+), 1448 deletions(-)

diff --git a/src/bin/psql/Makefile b/src/bin/psql/Makefile
index f1336d5..e4a3a2f 100644
--- a/src/bin/psql/Makefile
+++ b/src/bin/psql/Makefile
@@ -18,14 +18,12 @@ include $(top_builddir)/src/Makefile.global
 
 REFDOCDIR= $(top_srcdir)/doc/src/sgml/ref
 
-override CPPFLAGS := -I. -I$(srcdir) -I$(libpq_srcdir) -I$(top_srcdir)/src/bin/pg_dump $(CPPFLAGS)
+override CPPFLAGS := -I. -I$(regex_srcdir) -I$(srcdir) -I$(libpq_srcdir) -I$(top_srcdir)/src/bin/pg_dump $(CPPFLAGS)
 
 OBJS=	command.o common.o help.o input.o stringutils.o mainloop.o copy.o \
 	startup.o prompt.o variables.o large_obj.o print.o describe.o \
 	tab-complete.o mbprint.o dumputils.o keywords.o kwlookup.o \
-	sql_help.o \
-	$(WIN32RES)
-
+	sql_help.o $(top_srcdir)/src/backend/utils/mb/wstrncmp.o $(WIN32RES)
 
 all: psql
 
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index 55ace8a..89aeddb 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -54,6 +54,8 @@
 #include "common.h"
 #include "settings.h"
 #include "stringutils.h"
+#include "regex/regex.h"
+#include "catalog/pg_collation.h"
 
 #ifdef HAVE_RL_FILENAME_COMPLETION_FUNCTION
 #define filename_completion_function rl_filename_completion_function
@@ -134,6 +136,9 @@ static const char *completion_info_charp2;		/* to pass a third string */
 static const SchemaQuery *completion_squery;	/* to pass a SchemaQuery */
 static bool completion_case_sensitive;	/* completion is case sensitive */
 
+/* set true to stop regexp matching */
+static bool regmatch_stopped = false;;
+
 /*
  * A few macros to ease typing. You can use these to complete the given
  * string with
@@ -789,10 +794,53 @@ typedef struct
 	const bits32 flags;			/* visibility flags, see below */
 } pgsql_thing_t;
 
+/* This is a list of preprocessed (compiled) regular expressions */
+typedef struct re_hashent_t
+{
+	char *repat;				/* pointer to match pattern */
+	int	  cflags;				/* flags for pg_regcomp */
+	regex_t re;					/* compiled regular expression */
+	struct re_hashent_t *next;	/* next entry sharing the same hash */
+#ifdef DEBUG_COMPRE
+	char *restr;				/* intermediate regular expession */
+#endif
+} re_hashent;
+
+#define RE_HASH_SIZE 256		/* size of regexp hash table */
+static re_hashent re_hash[RE_HASH_SIZE];	/* regexp hash table */
+
 #define THING_NO_CREATE		(1 << 0)	/* should not show up after CREATE */
 #define THING_NO_DROP		(1 << 1)	/* should not show up after DROP */
 #define THING_NO_SHOW		(THING_NO_CREATE | THING_NO_DROP)
 
+#define CAPBUFLEN 128			/* storage length for each regexp capture
+								 * substr */
+#define MATCHNUM 8				/* maximum number of regexp capture  */
+
+/*
+ * Macros for patter matching.
+ * 
+ * MATCH matches the pattern case-insensitively.
+ * CMATCH matches the pattern case-sensitively.
+ * MATCHBEG returns start index of inebufw for designated capture string
+ * MATCHEND returns index of the next character in inebufw for designated
+ * 			capture string
+ * CAPTURE0 just copies match substr into capbuf.
+ * CAPTURE  captures match substr then returns it. CAPTURE0 then repeated
+ *          CAPBUF would be effective when captured substring is repeatedly
+ *          read.
+ * CAPBUF	returns capture buffer. 
+ */
+#define MATCH(pat) (rematch(linebufw, wstrlen, pat, rmatches, REG_ADVANCED|REG_ICASE))
+#define CMATCH(pat) (rematch(linebufw, wstrlen, pat, rmatches, REG_ADVANCED))
+#define MATCHBEG(n) (rmatches[n].rm_so)
+#define MATCHEND(n) (rmatches[n].rm_eo)
+#define MATCHLEN(n) (MATCHEND(n) - MATCHBEG(n))
+#define CAPCPYLEN(n)(MATCHLEN(n)<CAPBUFLEN ? MATCHLEN(n):CAPBUFLEN - 1)
+#define CAPTURE0(n) (strncpy(capbuf[n], linebuf + MATCHBEG(n), CAPCPYLEN(n)),capbuf[n][CAPCPYLEN(n)] = 0)
+#define CAPTURE(n)  (CAPTURE0(n), capbuf[n])
+#define CAPBUF(n)   (capbuf[n])
+
 static const pgsql_thing_t words_after_create[] = {
 	{"AGGREGATE", NULL, &Query_for_list_of_aggregates},
 	{"CAST", NULL, NULL},		/* Casts have complex structures for names, so
@@ -843,7 +891,6 @@ static const pgsql_thing_t words_after_create[] = {
 	{NULL}						/* end of list */
 };
 
-
 /* Forward declaration of functions */
 static char **psql_completion(const char *text, int start, int end);
 static char *create_command_generator(const char *text, int state);
@@ -865,15 +912,33 @@ static char *pg_strdup_keyword_case(const char *s, const char *ref);
 static char *escape_string(const char *text);
 static PGresult *exec_query(const char *query);
 
-static void get_previous_words(int point, char **previous_words, int nwords);
-
 static char *get_guctype(const char *varname);
 
+static uint32 hash_uint32(uint32 k);
+static int pathash(char *pat);
+static regex_t *patcomp(char *pat, int cflags);
+static bool rematch(pg_wchar *line, int linelen, char *pat, regmatch_t *rmatches, int cflags);
+
+
 #ifdef NOT_USED
 static char *quote_file_name(char *text, int match_type, char *quote_pointer);
 static char *dequote_file_name(char *text, char quote_char);
 #endif
 
+static int
+pg_ascii2wchar_with_len(const char *from, pg_wchar *to, int len)
+{
+	int			cnt = 0;
+
+	while (len > 0 && *from)
+	{
+		*to++ = *from++;
+		len--;
+		cnt++;
+	}
+	*to = 0;
+	return cnt;
+}
 
 /*
  * Initialize the readline library for our purposes.
@@ -894,6 +959,31 @@ initialize_readline(void)
 	 */
 }
 
+static pg_wchar *
+expand_wchar_buffer(pg_wchar *p, int *buflen, int newlen, int limit)
+{
+	pg_wchar *ret = p;
+	int       len1 = newlen - 1;
+
+	Assert(newlen > 0);
+	if (newlen >= *buflen)
+	{
+		int mask;
+
+		/* Allocate in size of 2^n. Minimum 256 wchars */
+		for (mask = 255 ; mask < limit && (len1 & mask) != len1 ;
+			 mask = (mask << 1) | 1);
+		
+		/* mask is (<new buffer length> - 1) here */
+		if (mask >= limit) return NULL; /* Exceeds limit */
+		
+		*buflen = mask + 1;
+		
+		ret = pg_realloc(p, (*buflen) * sizeof(pg_wchar));
+	}		
+
+	return ret;
+}
 
 /*
  * The completion function.
@@ -906,23 +996,16 @@ initialize_readline(void)
 static char **
 psql_completion(const char *text, int start, int end)
 {
+	const char *linebuf = rl_line_buffer;
+	static pg_wchar	 *linebufw = NULL;
+	static int	     linebufwlen = 0;
+	int len, wstrlen;
+	regmatch_t rmatches[MATCHNUM];
+	char capbuf[MATCHNUM][CAPBUFLEN];
+
 	/* This is the variable we'll return. */
 	char	  **matches = NULL;
 
-	/* This array will contain some scannage of the input line. */
-	char	   *previous_words[9];
-
-	/* For compactness, we use these macros to reference previous_words[]. */
-#define prev_wd   (previous_words[0])
-#define prev2_wd  (previous_words[1])
-#define prev3_wd  (previous_words[2])
-#define prev4_wd  (previous_words[3])
-#define prev5_wd  (previous_words[4])
-#define prev6_wd  (previous_words[5])
-#define prev7_wd  (previous_words[6])
-#define prev8_wd  (previous_words[7])
-#define prev9_wd  (previous_words[8])
-
 	static const char *const sql_commands[] = {
 		"ABORT", "ALTER", "ANALYZE", "BEGIN", "CHECKPOINT", "CLOSE", "CLUSTER",
 		"COMMENT", "COMMIT", "COPY", "CREATE", "DEALLOCATE", "DECLARE",
@@ -957,17 +1040,16 @@ psql_completion(const char *text, int start, int end)
 #endif
 
 	/* Clear a few things. */
+	regmatch_stopped = false;
 	completion_charp = NULL;
 	completion_charpp = NULL;
 	completion_info_charp = NULL;
 	completion_info_charp2 = NULL;
 
-	/*
-	 * Scan the input line before our current position for the last few words.
-	 * According to those we'll make some smart decisions on what the user is
-	 * probably intending to type.
-	 */
-	get_previous_words(start, previous_words, lengthof(previous_words));
+	len = strlen(linebuf);
+	/* Expand string buffer if needed */
+	linebufw = expand_wchar_buffer(linebufw, &linebufwlen, len + 1, 2048); 
+	wstrlen = pg_ascii2wchar_with_len(linebuf, linebufw, strlen(linebuf));
 
 	/* If a backslash command was started, continue */
 	if (text[0] == '\\')
@@ -985,36 +1067,31 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* If no previous word, suggest one of the basic sql commands */
-	else if (prev_wd[0] == '\0')
+	else if (MATCH("^"))
 		COMPLETE_WITH_LIST(sql_commands);
 
 /* CREATE */
 	/* complete with something you can create */
-	else if (pg_strcasecmp(prev_wd, "CREATE") == 0)
+	else if (MATCH("^CREATE"))
 		matches = completion_matches(text, create_command_generator);
 
 /* DROP, but not DROP embedded in other commands */
 	/* complete with something you can drop */
-	else if (pg_strcasecmp(prev_wd, "DROP") == 0 &&
-			 prev2_wd[0] == '\0')
+	else if (MATCH("^DROP"))
 		matches = completion_matches(text, drop_command_generator);
 
 /* ALTER */
 
 	/* ALTER TABLE */
-	else if (pg_strcasecmp(prev2_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev_wd, "TABLE") == 0)
-	{
+	else if (MATCH("^ALTER TABLE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
 								   "UNION SELECT 'ALL IN TABLESPACE'");
-	}
 
 	/*
 	 * complete with what you can alter (TABLE, GROUP, USER, ...) unless we're
 	 * in ALTER TABLE sth ALTER
 	 */
-	else if (pg_strcasecmp(prev_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TABLE") != 0)
+	else if (MATCH("^ALTER"))
 	{
 		static const char *const list_ALTER[] =
 		{"AGGREGATE", "COLLATION", "CONVERSION", "DATABASE", "DEFAULT PRIVILEGES", "DOMAIN",
@@ -1027,9 +1104,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTER);
 	}
 	/* ALTER TABLE,INDEX,MATERIALIZED VIEW xxx ALL IN TABLESPACE xxx */
-	else if (pg_strcasecmp(prev4_wd, "ALL") == 0 &&
-			 pg_strcasecmp(prev3_wd, "IN") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TABLESPACE") == 0)
+	else if (MATCH("ALL IN TABLESPACE #id"))
 	{
 		static const char *const list_ALTERALLINTSPC[] =
 		{"SET TABLESPACE", "OWNED BY", NULL};
@@ -1037,38 +1112,24 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERALLINTSPC);
 	}
 	/* ALTER TABLE,INDEX,MATERIALIZED VIEW xxx ALL IN TABLESPACE xxx OWNED BY */
-	else if (pg_strcasecmp(prev6_wd, "ALL") == 0 &&
-			 pg_strcasecmp(prev5_wd, "IN") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLESPACE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "OWNED") == 0 &&
-			 pg_strcasecmp(prev4_wd, "BY") == 0)
-	{
+	else if (MATCH("ALL IN TABLESPACE #id OWNED BY"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
-	}
 	/* ALTER AGGREGATE,FUNCTION <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "AGGREGATE") == 0 ||
-			  pg_strcasecmp(prev2_wd, "FUNCTION") == 0))
+	else if (MATCH("^ALTER {AGGREGATE|FUNCTION} #id"))
 		COMPLETE_WITH_CONST("(");
 	/* ALTER AGGREGATE,FUNCTION <name> (...) */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 (pg_strcasecmp(prev3_wd, "AGGREGATE") == 0 ||
-			  pg_strcasecmp(prev3_wd, "FUNCTION") == 0))
+	else if (MATCH("ALTER {AGGREGATE|FUNCTION} [#id](.."))
+		COMPLETE_WITH_FUNCTION_ARG(CAPTURE(1));
+	else if (MATCH("ALTER {AGGREGATE|FUNCTION} [#id](..)"))
 	{
-		if (prev_wd[strlen(prev_wd) - 1] == ')')
-		{
-			static const char *const list_ALTERAGG[] =
+		static const char *const list_ALTERAGG[] =
 			{"OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
 
-			COMPLETE_WITH_LIST(list_ALTERAGG);
-		}
-		else
-			COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
+		COMPLETE_WITH_LIST(list_ALTERAGG);
 	}
 
 	/* ALTER SCHEMA <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SCHEMA") == 0)
+	else if (MATCH("ALTER SCHEMA #id"))
 	{
 		static const char *const list_ALTERGEN[] =
 		{"OWNER TO", "RENAME TO", NULL};
@@ -1077,8 +1138,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER COLLATION <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "COLLATION") == 0)
+	else if (MATCH("ALTER COLLATION #id"))
 	{
 		static const char *const list_ALTERGEN[] =
 		{"OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
@@ -1087,8 +1147,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER CONVERSION <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "CONVERSION") == 0)
+	else if (MATCH("ALTER CONVERSION #id"))
 	{
 		static const char *const list_ALTERGEN[] =
 		{"OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
@@ -1097,8 +1156,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER DATABASE <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DATABASE") == 0)
+	else if (MATCH("ALTER DATABASE #id"))
 	{
 		static const char *const list_ALTERDATABASE[] =
 		{"RESET", "SET", "OWNER TO", "RENAME TO", "IS_TEMPLATE",
@@ -1108,17 +1166,13 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER EVENT TRIGGER */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "EVENT") == 0 &&
-			 pg_strcasecmp(prev_wd, "TRIGGER") == 0)
+	else if (MATCH("ALTER EVENT TRIGGER"))
 	{
 		COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers, NULL);
 	}
 
 	/* ALTER EVENT TRIGGER <name> */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "EVENT") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TRIGGER") == 0)
+	else if (MATCH("ALTER EVENT TRIGGER #id"))
 	{
 		static const char *const list_ALTER_EVENT_TRIGGER[] =
 		{"DISABLE", "ENABLE", "OWNER TO", "RENAME TO", NULL};
@@ -1127,10 +1181,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER EVENT TRIGGER <name> ENABLE */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "EVENT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TRIGGER") == 0 &&
-			 pg_strcasecmp(prev_wd, "ENABLE") == 0)
+	else if (MATCH("ALTER EVENT TRIGGER #id ENABLE"))
 	{
 		static const char *const list_ALTER_EVENT_TRIGGER_ENABLE[] =
 		{"REPLICA", "ALWAYS", NULL};
@@ -1139,8 +1190,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER EXTENSION <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "EXTENSION") == 0)
+	else if (MATCH("ALTER EXTENSION #id"))
 	{
 		static const char *const list_ALTEREXTENSION[] =
 		{"ADD", "DROP", "UPDATE", "SET SCHEMA", NULL};
@@ -1149,8 +1199,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER FOREIGN */
-	else if (pg_strcasecmp(prev2_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOREIGN") == 0)
+	else if (MATCH("ALTER FOREIGN"))
 	{
 		static const char *const list_ALTER_FOREIGN[] =
 		{"DATA WRAPPER", "TABLE", NULL};
@@ -1159,10 +1208,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER FOREIGN DATA WRAPPER <name> */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "FOREIGN") == 0 &&
-			 pg_strcasecmp(prev3_wd, "DATA") == 0 &&
-			 pg_strcasecmp(prev2_wd, "WRAPPER") == 0)
+	else if (MATCH("ALTER FOREIGN DATA WRAPPER #id"))
 	{
 		static const char *const list_ALTER_FDW[] =
 		{"HANDLER", "VALIDATOR", "OPTIONS", "OWNER TO", NULL};
@@ -1171,9 +1217,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER FOREIGN TABLE <name> */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "FOREIGN") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TABLE") == 0)
+	else if (MATCH("ALTER FOREIGN TABLE #id"))
 	{
 		static const char *const list_ALTER_FOREIGN_TABLE[] =
 		{"ADD", "ALTER", "DISABLE TRIGGER", "DROP", "ENABLE", "INHERIT",
@@ -1184,15 +1228,13 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER INDEX */
-	else if (pg_strcasecmp(prev2_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev_wd, "INDEX") == 0)
+	else if (MATCH("ALTER INDEX"))
 	{
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
 								   "UNION SELECT 'ALL IN TABLESPACE'");
 	}
 	/* ALTER INDEX <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "INDEX") == 0)
+	else if (MATCH("ALTER INDEX #id"))
 	{
 		static const char *const list_ALTERINDEX[] =
 		{"OWNER TO", "RENAME TO", "SET", "RESET", NULL};
@@ -1200,9 +1242,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERINDEX);
 	}
 	/* ALTER INDEX <name> SET */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "INDEX") == 0 &&
-			 pg_strcasecmp(prev_wd, "SET") == 0)
+	else if (MATCH("ALTER INDEX #id SET"))
 	{
 		static const char *const list_ALTERINDEXSET[] =
 		{"(", "TABLESPACE", NULL};
@@ -1210,25 +1250,17 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERINDEXSET);
 	}
 	/* ALTER INDEX <name> RESET */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "INDEX") == 0 &&
-			 pg_strcasecmp(prev_wd, "RESET") == 0)
+	else if (MATCH("ALTER INDEX #id RESET"))
 		COMPLETE_WITH_CONST("(");
 	/* ALTER INDEX <foo> SET|RESET ( */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "INDEX") == 0 &&
-			 pg_strcasecmp(prev2_wd, "RESET") == 0 &&
-			 pg_strcasecmp(prev_wd, "(") == 0)
+	else if (MATCH("ALTER INDEX #id RESET("))
 	{
 		static const char *const list_INDEXOPTIONS[] =
 		{"fillfactor", "fastupdate", "gin_pending_list_limit", NULL};
 
 		COMPLETE_WITH_LIST(list_INDEXOPTIONS);
 	}
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "INDEX") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev_wd, "(") == 0)
+	else if (MATCH("ALTER INDEX #id SET("))
 	{
 		static const char *const list_INDEXOPTIONS[] =
 		{"fillfactor =", "fastupdate =", "gin_pending_list_limit =", NULL};
@@ -1237,8 +1269,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER LANGUAGE <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "LANGUAGE") == 0)
+	else if (MATCH("ALTER LANGUAGE #id"))
 	{
 		static const char *const list_ALTERLANGUAGE[] =
 		{"OWNER TO", "RENAME TO", NULL};
@@ -1247,9 +1278,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER LARGE OBJECT <oid> */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "LARGE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "OBJECT") == 0)
+	else if (MATCH("ALTER LARGE OBJECT #id"))
 	{
 		static const char *const list_ALTERLARGEOBJECT[] =
 		{"OWNER TO", NULL};
@@ -1258,19 +1287,14 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER MATERIALIZED VIEW */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev_wd, "VIEW") == 0)
+	else if (MATCH("ALTER MATERIALIZED VIEW"))
 	{
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews,
 								   "UNION SELECT 'ALL IN TABLESPACE'");
 	}
 
 	/* ALTER USER,ROLE <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 !(pg_strcasecmp(prev2_wd, "USER") == 0 && pg_strcasecmp(prev_wd, "MAPPING") == 0) &&
-			 (pg_strcasecmp(prev2_wd, "USER") == 0 ||
-			  pg_strcasecmp(prev2_wd, "ROLE") == 0))
+	else if (MATCH("ALTER {{USER !MAPPING}|{ROLE #id}}"))
 	{
 		static const char *const list_ALTERUSER[] =
 		{"BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
@@ -1284,10 +1308,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER USER,ROLE <name> WITH */
-	else if ((pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			  (pg_strcasecmp(prev3_wd, "USER") == 0 ||
-			   pg_strcasecmp(prev3_wd, "ROLE") == 0) &&
-			  pg_strcasecmp(prev_wd, "WITH") == 0))
+	else if (MATCH("ALTER {USER|ROLE} #id WITH"))
 	{
 		/* Similar to the above, but don't complete "WITH" again. */
 		static const char *const list_ALTERUSER_WITH[] =
@@ -1302,16 +1323,11 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* complete ALTER USER,ROLE <name> ENCRYPTED,UNENCRYPTED with PASSWORD */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 (pg_strcasecmp(prev3_wd, "ROLE") == 0 || pg_strcasecmp(prev3_wd, "USER") == 0) &&
-			 (pg_strcasecmp(prev_wd, "ENCRYPTED") == 0 || pg_strcasecmp(prev_wd, "UNENCRYPTED") == 0))
-	{
+	else if (MATCH("ALTER {ROLE|USER} #id {UN}?ENCRYPTED"))
 		COMPLETE_WITH_CONST("PASSWORD");
-	}
+
 	/* ALTER DEFAULT PRIVILEGES */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DEFAULT") == 0 &&
-			 pg_strcasecmp(prev_wd, "PRIVILEGES") == 0)
+	else if (MATCH("ALTER DEFAULT PRIVILEGES"))
 	{
 		static const char *const list_ALTER_DEFAULT_PRIVILEGES[] =
 		{"FOR ROLE", "FOR USER", "IN SCHEMA", NULL};
@@ -1319,10 +1335,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTER_DEFAULT_PRIVILEGES);
 	}
 	/* ALTER DEFAULT PRIVILEGES FOR */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "DEFAULT") == 0 &&
-			 pg_strcasecmp(prev2_wd, "PRIVILEGES") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOR") == 0)
+	else if (MATCH("ALTER DEFAULT PRIVILEGES FOR"))
 	{
 		static const char *const list_ALTER_DEFAULT_PRIVILEGES_FOR[] =
 		{"ROLE", "USER", NULL};
@@ -1330,10 +1343,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTER_DEFAULT_PRIVILEGES_FOR);
 	}
 	/* ALTER DEFAULT PRIVILEGES { FOR ROLE ... | IN SCHEMA ... } */
-	else if (pg_strcasecmp(prev5_wd, "DEFAULT") == 0 &&
-			 pg_strcasecmp(prev4_wd, "PRIVILEGES") == 0 &&
-			 (pg_strcasecmp(prev3_wd, "FOR") == 0 ||
-			  pg_strcasecmp(prev3_wd, "IN") == 0))
+	else if (MATCH("DEFAULT PRIVILEGES {FOR|IN} #kwd #id"))
 	{
 		static const char *const list_ALTER_DEFAULT_PRIVILEGES_REST[] =
 		{"GRANT", "REVOKE", NULL};
@@ -1341,8 +1351,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTER_DEFAULT_PRIVILEGES_REST);
 	}
 	/* ALTER DOMAIN <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DOMAIN") == 0)
+	else if (MATCH("ALTER DOMAIN #id"))
 	{
 		static const char *const list_ALTERDOMAIN[] =
 		{"ADD", "DROP", "OWNER TO", "RENAME", "SET", "VALIDATE CONSTRAINT", NULL};
@@ -1350,9 +1359,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERDOMAIN);
 	}
 	/* ALTER DOMAIN <sth> DROP */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "DOMAIN") == 0 &&
-			 pg_strcasecmp(prev_wd, "DROP") == 0)
+	else if (MATCH("ALTER DOMAIN #id DROP"))
 	{
 		static const char *const list_ALTERDOMAIN2[] =
 		{"CONSTRAINT", "DEFAULT", "NOT NULL", NULL};
@@ -1360,19 +1367,11 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERDOMAIN2);
 	}
 	/* ALTER DOMAIN <sth> DROP|RENAME|VALIDATE CONSTRAINT */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "DOMAIN") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "DROP") == 0 ||
-			  pg_strcasecmp(prev2_wd, "RENAME") == 0 ||
-			  pg_strcasecmp(prev2_wd, "VALIDATE") == 0) &&
-			 pg_strcasecmp(prev_wd, "CONSTRAINT") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_constraint_of_type, prev3_wd);
-	}
+	else if (MATCH("ALTER DOMAIN [#id] {DROP|RENAME|VALIDATE} CONSTRAINT"))
+		COMPLETE_WITH_QUERY(Query_for_constraint_of_type, CAPTURE(1));
+
 	/* ALTER DOMAIN <sth> RENAME */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "DOMAIN") == 0 &&
-			 pg_strcasecmp(prev_wd, "RENAME") == 0)
+	else if (MATCH("ALTER DOMAIN #id RENAME"))
 	{
 		static const char *const list_ALTERDOMAIN[] =
 		{"CONSTRAINT", "TO", NULL};
@@ -1380,15 +1379,11 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERDOMAIN);
 	}
 	/* ALTER DOMAIN <sth> RENAME CONSTRAINT <sth> */
-	else if (pg_strcasecmp(prev5_wd, "DOMAIN") == 0 &&
-			 pg_strcasecmp(prev3_wd, "RENAME") == 0 &&
-			 pg_strcasecmp(prev2_wd, "CONSTRAINT") == 0)
+	else if (MATCH("ALTER DOMAIN #id RENAME CONSTRAINT #id"))
 		COMPLETE_WITH_CONST("TO");
 
 	/* ALTER DOMAIN <sth> SET */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "DOMAIN") == 0 &&
-			 pg_strcasecmp(prev_wd, "SET") == 0)
+	else if (MATCH("ALTER DOMAIN #id SET"))
 	{
 		static const char *const list_ALTERDOMAIN3[] =
 		{"DEFAULT", "NOT NULL", "SCHEMA", NULL};
@@ -1396,8 +1391,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERDOMAIN3);
 	}
 	/* ALTER SEQUENCE <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SEQUENCE") == 0)
+	else if (MATCH("ALTER SEQUENCE #id"))
 	{
 		static const char *const list_ALTERSEQUENCE[] =
 		{"INCREMENT", "MINVALUE", "MAXVALUE", "RESTART", "NO", "CACHE", "CYCLE",
@@ -1406,9 +1400,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERSEQUENCE);
 	}
 	/* ALTER SEQUENCE <name> NO */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "SEQUENCE") == 0 &&
-			 pg_strcasecmp(prev_wd, "NO") == 0)
+	else if (MATCH("ALTER SEQUENCE #id NO"))
 	{
 		static const char *const list_ALTERSEQUENCE2[] =
 		{"MINVALUE", "MAXVALUE", "CYCLE", NULL};
@@ -1416,8 +1408,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERSEQUENCE2);
 	}
 	/* ALTER SERVER <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SERVER") == 0)
+	else if (MATCH("ALTER SERVER #id"))
 	{
 		static const char *const list_ALTER_SERVER[] =
 		{"VERSION", "OPTIONS", "OWNER TO", NULL};
@@ -1425,8 +1416,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTER_SERVER);
 	}
 	/* ALTER SYSTEM SET, RESET, RESET ALL */
-	else if (pg_strcasecmp(prev2_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev_wd, "SYSTEM") == 0)
+	else if (MATCH("ALTER SYSTEM"))
 	{
 		static const char *const list_ALTERSYSTEM[] =
 		{"SET", "RESET", NULL};
@@ -1434,14 +1424,11 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERSYSTEM);
 	}
 	/* ALTER SYSTEM SET|RESET <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SYSTEM") == 0 &&
-			 (pg_strcasecmp(prev_wd, "SET") == 0 ||
-			  pg_strcasecmp(prev_wd, "RESET") == 0))
+	else if (MATCH("ALTER SYSTEM {SET|RESET}"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_alter_system_set_vars, NULL);
+
 	/* ALTER VIEW <name> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "VIEW") == 0)
+	else if (MATCH("ALTER VIEW #id"))
 	{
 		static const char *const list_ALTERVIEW[] =
 		{"ALTER COLUMN", "OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
@@ -1449,9 +1436,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERVIEW);
 	}
 	/* ALTER MATERIALIZED VIEW <name> */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev2_wd, "VIEW") == 0)
+	else if (MATCH("ALTER MATERIALIZED VIEW #id"))
 	{
 		static const char *const list_ALTERMATVIEW[] =
 		{"ALTER COLUMN", "OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
@@ -1460,18 +1445,15 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER POLICY <name> ON */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "POLICY") == 0)
+	else if (MATCH("ALTER POLICY #id"))
 		COMPLETE_WITH_CONST("ON");
+
 	/* ALTER POLICY <name> ON <table> */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
+	else if (MATCH("ALTER POLICY #id ON"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+
 	/* ALTER POLICY <name> ON <table> - show options */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0)
+	else if (MATCH("ALTER POLICY #id ON #id"))
 	{
 		static const char *const list_ALTERPOLICY[] =
 		{"RENAME TO", "TO", "USING", "WITH CHECK", NULL};
@@ -1479,72 +1461,51 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERPOLICY);
 	}
 	/* ALTER POLICY <name> ON <table> TO <role> */
-	else if (pg_strcasecmp(prev6_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev5_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "TO") == 0)
+	else if (MATCH("ALTER POLICY #id ON #id TO"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles, NULL);
+
 	/* ALTER POLICY <name> ON <table> USING ( */
-	else if (pg_strcasecmp(prev6_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev5_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "USING") == 0)
+	else if (MATCH("ALTER POLICY #id ON #id USING"))
 		COMPLETE_WITH_CONST("(");
+
 	/* ALTER POLICY <name> ON <table> WITH CHECK ( */
-	else if (pg_strcasecmp(prev6_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev4_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev2_wd, "WITH") == 0 &&
-			 pg_strcasecmp(prev_wd, "CHECK") == 0)
+	else if (MATCH("ALTER POLICY #id ON #id WITH CHECK"))
 		COMPLETE_WITH_CONST("(");
 
 	/* ALTER RULE <name>, add ON */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "RULE") == 0)
+	else if (MATCH("ALTER RULE #id"))
 		COMPLETE_WITH_CONST("ON");
 
 	/* If we have ALTER RULE <name> ON, then add the correct tablename */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "RULE") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_rule, prev2_wd);
-	}
+	else if (MATCH("ALTER RULE [#id] ON"))
+		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_rule, CAPTURE(1));
 
 	/* ALTER RULE <name> ON <name> */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "RULE") == 0)
+	else if (MATCH("ALTER RULE #id ON #id"))
 		COMPLETE_WITH_CONST("RENAME TO");
 
 	/* ALTER TRIGGER <name>, add ON */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TRIGGER") == 0)
+	else if (MATCH("ALTER TRIGGER #id"))
 		COMPLETE_WITH_CONST("ON");
 
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TRIGGER") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger, prev2_wd);
-	}
+	else if (MATCH("ALTER TRIGGER [#id] ON"))
+		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger, CAPTURE(1));
 
-	/*
-	 * If we have ALTER TRIGGER <sth> ON, then add the correct tablename
-	 */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TRIGGER") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
-		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+//  !!! This duplicates with the entry just above
+//	/*
+//	 * If we have ALTER TRIGGER <sth> ON, then add the correct tablename
+//	 */
+//	else if (MATCH("ALTER TRIGGER #id ON"))
+//		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
 
 	/* ALTER TRIGGER <name> ON <name> */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TRIGGER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0)
+	else if (MATCH("ALTER TRIGGER #id ON #id"))
 		COMPLETE_WITH_CONST("RENAME TO");
 
 	/*
 	 * If we detect ALTER TABLE <name>, suggest sub commands
 	 */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TABLE") == 0)
+	else if (MATCH("ALTER TABLE #id"))
 	{
 		static const char *const list_ALTER2[] =
 		{"ADD", "ALTER", "CLUSTER ON", "DISABLE", "DROP", "ENABLE", "INHERIT",
@@ -1554,96 +1515,55 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTER2);
 	}
 	/* ALTER TABLE xxx ENABLE */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "ENABLE") == 0)
+	else if (MATCH("ALTER TABLE #id ENABLE"))
 	{
 		static const char *const list_ALTERENABLE[] =
 		{"ALWAYS", "REPLICA", "ROW LEVEL SECURITY", "RULE", "TRIGGER", NULL};
 
 		COMPLETE_WITH_LIST(list_ALTERENABLE);
 	}
-	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ENABLE") == 0 &&
-			 (pg_strcasecmp(prev_wd, "REPLICA") == 0 ||
-			  pg_strcasecmp(prev_wd, "ALWAYS") == 0))
+	else if (MATCH("ALTER TABLE #id ENABLE {REPLICA|ALWAYS}"))
 	{
 		static const char *const list_ALTERENABLE2[] =
 		{"RULE", "TRIGGER", NULL};
 
 		COMPLETE_WITH_LIST(list_ALTERENABLE2);
 	}
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ENABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "RULE") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_rule_of_table, prev3_wd);
-	}
-	else if (pg_strcasecmp(prev6_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev5_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ENABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "RULE") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_rule_of_table, prev4_wd);
-	}
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ENABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "TRIGGER") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_trigger_of_table, prev3_wd);
-	}
-	else if (pg_strcasecmp(prev6_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev5_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ENABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "TRIGGER") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_trigger_of_table, prev4_wd);
-	}
+	else if (MATCH("ALTER TABLE [#id] ENABLE RULE"))
+		COMPLETE_WITH_QUERY(Query_for_rule_of_table, CAPTURE(1));
+
+	else if (MATCH("ALTER TABLE [#id] ENABLE #kwd RULE"))
+		COMPLETE_WITH_QUERY(Query_for_rule_of_table, CAPTURE(1));
+
+	else if (MATCH("ALTER TABLE [#id] ENABLE TRIGGER"))
+		COMPLETE_WITH_QUERY(Query_for_trigger_of_table, CAPTURE(1));
+
+	else if (MATCH("ALTER TABLE [#id] ENABLE #kwd TRIGGER"))
+		COMPLETE_WITH_QUERY(Query_for_trigger_of_table, CAPTURE(1));
+
 	/* ALTER TABLE xxx INHERIT */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "INHERIT") == 0)
-	{
+	else if (MATCH("ALTER TABLE #id INHERIT"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
-	}
+
 	/* ALTER TABLE xxx NO INHERIT */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "NO") == 0 &&
-			 pg_strcasecmp(prev_wd, "INHERIT") == 0)
-	{
+	else if (MATCH("ALTER TABLE #id NO INHERIT"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
-	}
+
 	/* ALTER TABLE xxx DISABLE */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "DISABLE") == 0)
+	else if (MATCH("ALTER TABLE #id DISABLE"))
 	{
 		static const char *const list_ALTERDISABLE[] =
 		{"ROW LEVEL SECURITY", "RULE", "TRIGGER", NULL};
 
 		COMPLETE_WITH_LIST(list_ALTERDISABLE);
 	}
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DISABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "RULE") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_rule_of_table, prev3_wd);
-	}
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DISABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "TRIGGER") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_trigger_of_table, prev3_wd);
-	}
-	else if (pg_strcasecmp(prev4_wd, "DISABLE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ROW") == 0 &&
-			 pg_strcasecmp(prev2_wd, "LEVEL") == 0 &&
-			 pg_strcasecmp(prev_wd, "SECURITY") == 0)
+	else if (MATCH("ALTER TABLE [#id] DISABLE RULE"))
+		COMPLETE_WITH_QUERY(Query_for_rule_of_table, CAPTURE(1));
+
+	else if (MATCH("ALTER TABLE [#id] DISABLE TRIGGER"))
+		COMPLETE_WITH_QUERY(Query_for_trigger_of_table, CAPTURE(1));
+
+	else if (MATCH("DISABLE ROW LEVEL SECURITY"))
 	{
 		static const char *const list_DISABLERLS[] =
 		{"CASCADE", NULL};
@@ -1652,45 +1572,33 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER TABLE xxx ALTER */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "ALTER") == 0)
-		COMPLETE_WITH_ATTR(prev2_wd, " UNION SELECT 'COLUMN' UNION SELECT 'CONSTRAINT'");
+	else if (MATCH("ALTER TABLE [#id] ALTER"))
+		COMPLETE_WITH_ATTR(CAPTURE(1), " UNION SELECT 'COLUMN' UNION SELECT 'CONSTRAINT'");
 
 	/* ALTER TABLE xxx RENAME */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "RENAME") == 0)
-		COMPLETE_WITH_ATTR(prev2_wd, " UNION SELECT 'COLUMN' UNION SELECT 'CONSTRAINT' UNION SELECT 'TO'");
+	else if (MATCH("ALTER TABLE [#id] RENAME"))
+		COMPLETE_WITH_ATTR(CAPTURE(1),
+						   " UNION SELECT 'COLUMN'"
+						   " UNION SELECT 'CONSTRAINT'"
+						   " UNION SELECT 'TO'");
 
 	/*
 	 * If we have TABLE <sth> ALTER COLUMN|RENAME COLUMN, provide list of
 	 * columns
 	 */
-	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "ALTER") == 0 ||
-			  pg_strcasecmp(prev2_wd, "RENAME") == 0) &&
-			 pg_strcasecmp(prev_wd, "COLUMN") == 0)
-		COMPLETE_WITH_ATTR(prev3_wd, "");
+	else if (MATCH("TABLE [#id] {ALTER|RENAME} COLUMN"))
+		COMPLETE_WITH_ATTR(CAPTURE(1), "");
 
 	/* ALTER TABLE xxx RENAME yyy */
-	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "RENAME") == 0 &&
-			 pg_strcasecmp(prev_wd, "CONSTRAINT") != 0 &&
-			 pg_strcasecmp(prev_wd, "TO") != 0)
+	else if (MATCH("TABLE #id RENAME !CONSTRAINT|TO"))
 		COMPLETE_WITH_CONST("TO");
 
 	/* ALTER TABLE xxx RENAME COLUMN/CONSTRAINT yyy */
-	else if (pg_strcasecmp(prev5_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "RENAME") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "COLUMN") == 0 ||
-			  pg_strcasecmp(prev2_wd, "CONSTRAINT") == 0) &&
-			 pg_strcasecmp(prev_wd, "TO") != 0)
+	else if (MATCH("TABLE #id RENAME {COLUMN|CONSTRAINT} !TO"))
 		COMPLETE_WITH_CONST("TO");
 
 	/* If we have TABLE <sth> DROP, provide COLUMN or CONSTRAINT */
-	else if (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "DROP") == 0)
+	else if (MATCH("TABLE #id DROP"))
 	{
 		static const char *const list_TABLEDROP[] =
 		{"COLUMN", "CONSTRAINT", NULL};
@@ -1698,31 +1606,18 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_TABLEDROP);
 	}
 	/* If we have ALTER TABLE <sth> DROP COLUMN, provide list of columns */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev_wd, "COLUMN") == 0)
-		COMPLETE_WITH_ATTR(prev3_wd, "");
+	else if (MATCH("ALTER TABLE [#id] DROP COLUMN"))
+		COMPLETE_WITH_ATTR(CAPTURE(1), "");
 
 	/*
 	 * If we have ALTER TABLE <sth> ALTER|DROP|RENAME|VALIDATE CONSTRAINT,
 	 * provide list of constraints
 	 */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "ALTER") == 0 ||
-			  pg_strcasecmp(prev2_wd, "DROP") == 0 ||
-			  pg_strcasecmp(prev2_wd, "RENAME") == 0 ||
-			  pg_strcasecmp(prev2_wd, "VALIDATE") == 0) &&
-			 pg_strcasecmp(prev_wd, "CONSTRAINT") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_constraint_of_table, prev3_wd);
-	}
+	else if (MATCH("ALTER TABLE [#id] {DROP|RENAME|VALIDATE} CONSTRAINT"))
+		COMPLETE_WITH_QUERY(Query_for_constraint_of_table, CAPTURE(1));
+
 	/* ALTER TABLE ALTER [COLUMN] <foo> */
-	else if ((pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			  pg_strcasecmp(prev2_wd, "COLUMN") == 0) ||
-			 (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			  pg_strcasecmp(prev2_wd, "ALTER") == 0))
+	else if (MATCH("ALTER TABLE #id ALTER {COLUMN }? #id"))
 	{
 		static const char *const list_COLUMNALTER[] =
 		{"TYPE", "SET", "RESET", "DROP", NULL};
@@ -1730,11 +1625,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_COLUMNALTER);
 	}
 	/* ALTER TABLE ALTER [COLUMN] <foo> SET */
-	else if (((pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			   pg_strcasecmp(prev3_wd, "COLUMN") == 0) ||
-			  (pg_strcasecmp(prev5_wd, "TABLE") == 0 &&
-			   pg_strcasecmp(prev3_wd, "ALTER") == 0)) &&
-			 pg_strcasecmp(prev_wd, "SET") == 0)
+	else if (MATCH("ALTER TABLE #id ALTER {COLUMN }? #id SET"))
 	{
 		static const char *const list_COLUMNSET[] =
 		{"(", "DEFAULT", "NOT NULL", "STATISTICS", "STORAGE", NULL};
@@ -1742,11 +1633,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_COLUMNSET);
 	}
 	/* ALTER TABLE ALTER [COLUMN] <foo> SET ( */
-	else if (((pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			   pg_strcasecmp(prev4_wd, "COLUMN") == 0) ||
-			  pg_strcasecmp(prev4_wd, "ALTER") == 0) &&
-			 pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev_wd, "(") == 0)
+	else if (MATCH("ALTER TABLE #id ALTER {COLUMN }? #id SET ("))
 	{
 		static const char *const list_COLUMNOPTIONS[] =
 		{"n_distinct", "n_distinct_inherited", NULL};
@@ -1754,11 +1641,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_COLUMNOPTIONS);
 	}
 	/* ALTER TABLE ALTER [COLUMN] <foo> SET STORAGE */
-	else if (((pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			   pg_strcasecmp(prev4_wd, "COLUMN") == 0) ||
-			  pg_strcasecmp(prev4_wd, "ALTER") == 0) &&
-			 pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev_wd, "STORAGE") == 0)
+	else if (MATCH("ALTER TABLE #id ALTER {COLUMN }? #id SET STORAGE"))
 	{
 		static const char *const list_COLUMNSTORAGE[] =
 		{"PLAIN", "EXTERNAL", "EXTENDED", "MAIN", NULL};
@@ -1766,29 +1649,21 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_COLUMNSTORAGE);
 	}
 	/* ALTER TABLE ALTER [COLUMN] <foo> DROP */
-	else if (((pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			   pg_strcasecmp(prev3_wd, "COLUMN") == 0) ||
-			  (pg_strcasecmp(prev5_wd, "TABLE") == 0 &&
-			   pg_strcasecmp(prev3_wd, "ALTER") == 0)) &&
-			 pg_strcasecmp(prev_wd, "DROP") == 0)
+	else if (MATCH("ALTER TABLE #id ALTER {COLUMN }? #id DROP"))
 	{
 		static const char *const list_COLUMNDROP[] =
 		{"DEFAULT", "NOT NULL", NULL};
 
 		COMPLETE_WITH_LIST(list_COLUMNDROP);
 	}
-	else if (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "CLUSTER") == 0)
+	else if (MATCH("ALTER TABLE #id CLUSTER"))
 		COMPLETE_WITH_CONST("ON");
-	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "CLUSTER") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_index_of_table, prev3_wd);
-	}
+
+	else if (MATCH("ALTER TABLE [#id] CLUSTER ON"))
+		COMPLETE_WITH_QUERY(Query_for_index_of_table, CAPTURE(1));
+
 	/* If we have TABLE <sth> SET, provide list of attributes and '(' */
-	else if (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "SET") == 0)
+	else if (MATCH("ALTER TABLE #id SET"))
 	{
 		static const char *const list_TABLESET[] =
 		{"(", "LOGGED", "SCHEMA", "TABLESPACE", "UNLOGGED", "WITH", "WITHOUT", NULL};
@@ -1796,14 +1671,11 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_TABLESET);
 	}
 	/* If we have TABLE <sth> SET TABLESPACE provide a list of tablespaces */
-	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev_wd, "TABLESPACE") == 0)
+	else if (MATCH("ALTER TABLE #id SET TABLESPACE"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces, NULL);
+
 	/* If we have TABLE <sth> SET WITHOUT provide CLUSTER or OIDS */
-	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev_wd, "WITHOUT") == 0)
+	else if (MATCH("ALTER TABLE #id SET WITHOUT"))
 	{
 		static const char *const list_TABLESET2[] =
 		{"CLUSTER", "OIDS", NULL};
@@ -1811,14 +1683,11 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_TABLESET2);
 	}
 	/* ALTER TABLE <foo> RESET */
-	else if (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "RESET") == 0)
+	else if (MATCH("ALTER TABLE #id RESET"))
 		COMPLETE_WITH_CONST("(");
+
 	/* ALTER TABLE <foo> SET|RESET ( */
-	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "SET") == 0 ||
-			  pg_strcasecmp(prev2_wd, "RESET") == 0) &&
-			 pg_strcasecmp(prev_wd, "(") == 0)
+	else if (MATCH("ALTER TABLE #id {RE}?SET("))
 	{
 		static const char *const list_TABLEOPTIONS[] =
 		{
@@ -1855,38 +1724,24 @@ psql_completion(const char *text, int start, int end)
 
 		COMPLETE_WITH_LIST(list_TABLEOPTIONS);
 	}
-	else if (pg_strcasecmp(prev4_wd, "REPLICA") == 0 &&
-			 pg_strcasecmp(prev3_wd, "IDENTITY") == 0 &&
-			 pg_strcasecmp(prev2_wd, "USING") == 0 &&
-			 pg_strcasecmp(prev_wd, "INDEX") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_index_of_table, prev5_wd);
-	}
-	else if (pg_strcasecmp(prev5_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "REPLICA") == 0 &&
-			 pg_strcasecmp(prev2_wd, "IDENTITY") == 0 &&
-			 pg_strcasecmp(prev_wd, "USING") == 0)
-	{
+	else if (MATCH("[#id] REPLICA IDENTITY USING INDEX"))
+		COMPLETE_WITH_QUERY(Query_for_index_of_table, CAPTURE(1));
+
+	else if (MATCH("TABLE #id REPLICA IDENTITY USING"))
 		COMPLETE_WITH_CONST("INDEX");
-	}
-	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "REPLICA") == 0 &&
-			 pg_strcasecmp(prev_wd, "IDENTITY") == 0)
+
+	else if (MATCH("TABLE #id REPLICA IDENTITY"))
 	{
 		static const char *const list_REPLICAID[] =
 		{"FULL", "NOTHING", "DEFAULT", "USING", NULL};
 
 		COMPLETE_WITH_LIST(list_REPLICAID);
 	}
-	else if (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev_wd, "REPLICA") == 0)
-	{
+	else if (MATCH("TABLE #id REPLICA"))
 		COMPLETE_WITH_CONST("IDENTITY");
-	}
 
 	/* ALTER TABLESPACE <foo> with RENAME TO, OWNER TO, SET, RESET */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TABLESPACE") == 0)
+	else if (MATCH("ALTER TABLESPACE #id"))
 	{
 		static const char *const list_ALTERTSPC[] =
 		{"RENAME TO", "OWNER TO", "SET", "RESET", NULL};
@@ -1894,17 +1749,11 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERTSPC);
 	}
 	/* ALTER TABLESPACE <foo> SET|RESET */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TABLESPACE") == 0 &&
-			 (pg_strcasecmp(prev_wd, "SET") == 0 ||
-			  pg_strcasecmp(prev_wd, "RESET") == 0))
+	else if (MATCH("ALTER TABLESPACE #id {RE}?SET"))
 		COMPLETE_WITH_CONST("(");
+
 	/* ALTER TABLESPACE <foo> SET|RESET ( */
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLESPACE") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "SET") == 0 ||
-			  pg_strcasecmp(prev2_wd, "RESET") == 0) &&
-			 pg_strcasecmp(prev_wd, "(") == 0)
+	else if (MATCH("ALTER TABLESPACE #id {RE}?SET("))
 	{
 		static const char *const list_TABLESPACEOPTIONS[] =
 		{"seq_page_cost", "random_page_cost", "effective_io_concurrency", NULL};
@@ -1913,20 +1762,14 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* ALTER TEXT SEARCH */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TEXT") == 0 &&
-			 pg_strcasecmp(prev_wd, "SEARCH") == 0)
+	else if (MATCH("ALTER TEXT SEARCH"))
 	{
 		static const char *const list_ALTERTEXTSEARCH[] =
 		{"CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE", NULL};
 
 		COMPLETE_WITH_LIST(list_ALTERTEXTSEARCH);
 	}
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TEXT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "SEARCH") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "TEMPLATE") == 0 ||
-			  pg_strcasecmp(prev2_wd, "PARSER") == 0))
+	else if (MATCH("ALTER TEXT SEARCH {TEMPLATE|PARSER} #id"))
 	{
 		static const char *const list_ALTERTEXTSEARCH2[] =
 		{"RENAME TO", "SET SCHEMA", NULL};
@@ -1934,10 +1777,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERTEXTSEARCH2);
 	}
 
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TEXT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "SEARCH") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DICTIONARY") == 0)
+	else if (MATCH("ALTER TEXT SEARCH DICTIONARY #id"))
 	{
 		static const char *const list_ALTERTEXTSEARCH3[] =
 		{"OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
@@ -1945,10 +1785,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERTEXTSEARCH3);
 	}
 
-	else if (pg_strcasecmp(prev5_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TEXT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "SEARCH") == 0 &&
-			 pg_strcasecmp(prev2_wd, "CONFIGURATION") == 0)
+	else if (MATCH("ALTER TEXT SEARCH CONFIGURATION #id"))
 	{
 		static const char *const list_ALTERTEXTSEARCH4[] =
 		{"ADD MAPPING FOR", "ALTER MAPPING", "DROP MAPPING FOR", "OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
@@ -1957,8 +1794,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* complete ALTER TYPE <foo> with actions */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TYPE") == 0)
+	else if (MATCH("ALTER TYPE #id"))
 	{
 		static const char *const list_ALTERTYPE[] =
 		{"ADD ATTRIBUTE", "ADD VALUE", "ALTER ATTRIBUTE", "DROP ATTRIBUTE",
@@ -1967,9 +1803,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERTYPE);
 	}
 	/* complete ALTER TYPE <foo> ADD with actions */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TYPE") == 0 &&
-			 pg_strcasecmp(prev_wd, "ADD") == 0)
+	else if (MATCH("ALTER TYPE #id ADD"))
 	{
 		static const char *const list_ALTERTYPE[] =
 		{"ATTRIBUTE", "VALUE", NULL};
@@ -1977,9 +1811,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERTYPE);
 	}
 	/* ALTER TYPE <foo> RENAME	*/
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TYPE") == 0 &&
-			 pg_strcasecmp(prev_wd, "RENAME") == 0)
+	else if (MATCH("ALTER TYPE #id RENAME"))
 	{
 		static const char *const list_ALTERTYPE[] =
 		{"ATTRIBUTE", "TO", NULL};
@@ -1987,30 +1819,22 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERTYPE);
 	}
 	/* ALTER TYPE xxx RENAME ATTRIBUTE yyy */
-	else if (pg_strcasecmp(prev5_wd, "TYPE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "RENAME") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ATTRIBUTE") == 0)
+	else if (MATCH("TYPE #id RENAME ATTRIBUTE #id"))
 		COMPLETE_WITH_CONST("TO");
 
 	/*
 	 * If we have TYPE <sth> ALTER/DROP/RENAME ATTRIBUTE, provide list of
 	 * attributes
 	 */
-	else if (pg_strcasecmp(prev4_wd, "TYPE") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "ALTER") == 0 ||
-			  pg_strcasecmp(prev2_wd, "DROP") == 0 ||
-			  pg_strcasecmp(prev2_wd, "RENAME") == 0) &&
-			 pg_strcasecmp(prev_wd, "ATTRIBUTE") == 0)
-		COMPLETE_WITH_ATTR(prev3_wd, "");
+	else if (MATCH("TYPE [#id] {ALTER|DROP|RENAME} ATTRIBUTE"))
+		COMPLETE_WITH_ATTR(CAPTURE(1), "");
+
 	/* ALTER TYPE ALTER ATTRIBUTE <foo> */
-	else if ((pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			  pg_strcasecmp(prev2_wd, "ATTRIBUTE") == 0))
-	{
+	else if (MATCH("ALTER ATTRIBUTE #id"))
 		COMPLETE_WITH_CONST("TYPE");
-	}
+
 	/* complete ALTER GROUP <foo> */
-	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "GROUP") == 0)
+	else if (MATCH("ALTER GROUP #id"))
 	{
 		static const char *const list_ALTERGROUP[] =
 		{"ADD USER", "DROP USER", "RENAME TO", NULL};
@@ -2018,22 +1842,15 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_ALTERGROUP);
 	}
 	/* complete ALTER GROUP <foo> ADD|DROP with USER */
-	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "GROUP") == 0 &&
-			 (pg_strcasecmp(prev_wd, "ADD") == 0 ||
-			  pg_strcasecmp(prev_wd, "DROP") == 0))
+	else if (MATCH("ALTER GROUP #id {ADD|DROP}"))
 		COMPLETE_WITH_CONST("USER");
+
 	/* complete {ALTER} GROUP <foo> ADD|DROP USER with a user name */
-	else if (pg_strcasecmp(prev4_wd, "GROUP") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "ADD") == 0 ||
-			  pg_strcasecmp(prev2_wd, "DROP") == 0) &&
-			 pg_strcasecmp(prev_wd, "USER") == 0)
+	else if (MATCH("ALTER GROUP #id {ADD|DROP} USER"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
 
 /* BEGIN, END, ABORT */
-	else if (pg_strcasecmp(prev_wd, "BEGIN") == 0 ||
-			 pg_strcasecmp(prev_wd, "END") == 0 ||
-			 pg_strcasecmp(prev_wd, "ABORT") == 0)
+	else if (MATCH("{BEGIN|END|ABORT}"))
 	{
 		static const char *const list_TRANS[] =
 		{"WORK", "TRANSACTION", NULL};
@@ -2041,7 +1858,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_TRANS);
 	}
 /* COMMIT */
-	else if (pg_strcasecmp(prev_wd, "COMMIT") == 0)
+	else if (MATCH("COMMIT"))
 	{
 		static const char *const list_COMMIT[] =
 		{"WORK", "TRANSACTION", "PREPARED", NULL};
@@ -2049,10 +1866,11 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_COMMIT);
 	}
 /* RELEASE SAVEPOINT */
-	else if (pg_strcasecmp(prev_wd, "RELEASE") == 0)
+	else if (MATCH("RELEASE"))
 		COMPLETE_WITH_CONST("SAVEPOINT");
+
 /* ROLLBACK*/
-	else if (pg_strcasecmp(prev_wd, "ROLLBACK") == 0)
+	else if (MATCH("ROLLBACK"))
 	{
 		static const char *const list_TRANS[] =
 		{"WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED", NULL};
@@ -2064,125 +1882,83 @@ psql_completion(const char *text, int start, int end)
 	/*
 	 * If the previous word is CLUSTER and not WITHOUT produce list of tables
 	 */
-	else if (pg_strcasecmp(prev_wd, "CLUSTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "WITHOUT") != 0)
-		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, "UNION SELECT 'VERBOSE'");
+	else if (MATCH(" !WITHOUT CLUSTER"))
+		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm,
+								   "UNION SELECT 'VERBOSE'");
 
 	/*
 	 * If the previous words are CLUSTER VERBOSE produce list of tables
 	 */
-	else if (pg_strcasecmp(prev_wd, "VERBOSE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "CLUSTER") == 0)
+	else if (MATCH("CLUSTER VERBOSE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, NULL);
 
 	/* If we have CLUSTER <sth>, then add "USING" */
-	else if (pg_strcasecmp(prev2_wd, "CLUSTER") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") != 0 &&
-			 pg_strcasecmp(prev_wd, "VERBOSE") != 0)
-	{
+	else if (MATCH("CLUSTER !ON|VERBOSE"))
 		COMPLETE_WITH_CONST("USING");
-	}
+
 	/* If we have CLUSTER VERBOSE <sth>, then add "USING" */
-	else if (pg_strcasecmp(prev3_wd, "CLUSTER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "VERBOSE") == 0)
-	{
+	else if (MATCH("CLUSTER VERBOSE #id"))
 		COMPLETE_WITH_CONST("USING");
-	}
 
 	/*
 	 * If we have CLUSTER <sth> USING, then add the index as well.
 	 */
-	else if (pg_strcasecmp(prev3_wd, "CLUSTER") == 0 &&
-			 pg_strcasecmp(prev_wd, "USING") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_index_of_table, prev2_wd);
-	}
+	else if (MATCH("CLUSTER [#id] USING"))
+		COMPLETE_WITH_QUERY(Query_for_index_of_table, CAPTURE(1));
 
 	/*
 	 * If we have CLUSTER VERBOSE <sth> USING, then add the index as well.
 	 */
-	else if (pg_strcasecmp(prev4_wd, "CLUSTER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "VERBOSE") == 0 &&
-			 pg_strcasecmp(prev_wd, "USING") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_index_of_table, prev2_wd);
-	}
+	else if (MATCH("CLUSTER VERBOSE [#id] USING"))
+		COMPLETE_WITH_QUERY(Query_for_index_of_table, CAPTURE(1));
 
 /* COMMENT */
-	else if (pg_strcasecmp(prev_wd, "COMMENT") == 0)
+	else if (MATCH("COMMENT"))
 		COMPLETE_WITH_CONST("ON");
-	else if (pg_strcasecmp(prev2_wd, "COMMENT") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
+
+	else if (MATCH("COMMENT ON"))
 	{
 		static const char *const list_COMMENT[] =
-		{"CAST", "COLLATION", "CONVERSION", "DATABASE", "EVENT TRIGGER", "EXTENSION",
-			"FOREIGN DATA WRAPPER", "FOREIGN TABLE",
-			"SERVER", "INDEX", "LANGUAGE", "POLICY", "RULE", "SCHEMA", "SEQUENCE",
-			"TABLE", "TYPE", "VIEW", "MATERIALIZED VIEW", "COLUMN", "AGGREGATE", "FUNCTION",
-			"OPERATOR", "TRIGGER", "CONSTRAINT", "DOMAIN", "LARGE OBJECT",
-		"TABLESPACE", "TEXT SEARCH", "ROLE", NULL};
+		{"CAST", "COLLATION", "CONVERSION", "DATABASE", "EVENT TRIGGER",
+		 "EXTENSION", "FOREIGN DATA WRAPPER", "FOREIGN TABLE", "SERVER",
+		 "INDEX", "LANGUAGE", "POLICY", "RULE", "SCHEMA", "SEQUENCE",
+		 "TABLE", "TYPE", "VIEW", "MATERIALIZED VIEW", "COLUMN", "AGGREGATE",
+		 "FUNCTION", "OPERATOR", "TRIGGER", "CONSTRAINT", "DOMAIN",
+		 "LARGE OBJECT", "TABLESPACE", "TEXT SEARCH", "ROLE", NULL};
 
 		COMPLETE_WITH_LIST(list_COMMENT);
 	}
-	else if (pg_strcasecmp(prev3_wd, "COMMENT") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOREIGN") == 0)
+	else if (MATCH("COMMENT ON FOREIGN"))
 	{
 		static const char *const list_TRANS2[] =
 		{"DATA WRAPPER", "TABLE", NULL};
 
 		COMPLETE_WITH_LIST(list_TRANS2);
 	}
-	else if (pg_strcasecmp(prev4_wd, "COMMENT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TEXT") == 0 &&
-			 pg_strcasecmp(prev_wd, "SEARCH") == 0)
+	else if (MATCH("COMMENT ON TEXT SEARCH"))
 	{
 		static const char *const list_TRANS2[] =
 		{"CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE", NULL};
 
 		COMPLETE_WITH_LIST(list_TRANS2);
 	}
-	else if (pg_strcasecmp(prev3_wd, "COMMENT") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "CONSTRAINT") == 0)
-	{
+	else if (MATCH("COMMENT ON CONSTRAINT"))
 		COMPLETE_WITH_QUERY(Query_for_all_table_constraints, NULL);
-	}
-	else if (pg_strcasecmp(prev4_wd, "COMMENT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev2_wd, "CONSTRAINT") == 0)
-	{
+
+	else if (MATCH("COMMENT ON CONSTRAINT #id"))
 		COMPLETE_WITH_CONST("ON");
-	}
-	else if (pg_strcasecmp(prev5_wd, "COMMENT") == 0 &&
-			 pg_strcasecmp(prev4_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev3_wd, "CONSTRAINT") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_constraint, prev2_wd);
-	}
-	else if (pg_strcasecmp(prev4_wd, "COMMENT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev2_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev_wd, "VIEW") == 0)
-	{
+
+	else if (MATCH("COMMENT ON CONSTRAINT [#id] ON"))
+		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_constraint,
+							CAPTURE(1));
+
+	else if (MATCH("COMMENT ON MATERIALIZED VIEW"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
-	}
-	else if (pg_strcasecmp(prev4_wd, "COMMENT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev2_wd, "EVENT") == 0 &&
-			 pg_strcasecmp(prev_wd, "TRIGGER") == 0)
-	{
+
+	else if (MATCH("COMMENT ON EVENT TRIGGER"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers, NULL);
-	}
-	else if (((pg_strcasecmp(prev4_wd, "COMMENT") == 0 &&
-			   pg_strcasecmp(prev3_wd, "ON") == 0) ||
-			  (pg_strcasecmp(prev5_wd, "COMMENT") == 0 &&
-			   pg_strcasecmp(prev4_wd, "ON") == 0) ||
-			  (pg_strcasecmp(prev6_wd, "COMMENT") == 0 &&
-			   pg_strcasecmp(prev5_wd, "ON") == 0)) &&
-			 pg_strcasecmp(prev_wd, "IS") != 0)
+
+	else if (MATCH("COMMENT ON {#kwd }+ !IS"))
 		COMPLETE_WITH_CONST("IS");
 
 /* COPY */
@@ -2191,15 +1967,11 @@ psql_completion(const char *text, int start, int end)
 	 * If we have COPY [BINARY] (which you'd have to type yourself), offer
 	 * list of tables (Also cover the analogous backslash command)
 	 */
-	else if (pg_strcasecmp(prev_wd, "COPY") == 0 ||
-			 pg_strcasecmp(prev_wd, "\\copy") == 0 ||
-			 (pg_strcasecmp(prev2_wd, "COPY") == 0 &&
-			  pg_strcasecmp(prev_wd, "BINARY") == 0))
+	else if (MATCH("\\?COPY{ BINARY}?"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+
 	/* If we have COPY|BINARY <sth>, complete it with "TO" or "FROM" */
-	else if (pg_strcasecmp(prev2_wd, "COPY") == 0 ||
-			 pg_strcasecmp(prev2_wd, "\\copy") == 0 ||
-			 pg_strcasecmp(prev2_wd, "BINARY") == 0)
+	else if (MATCH("\\?COPY{ BINARY}? #id"))
 	{
 		static const char *const list_FROMTO[] =
 		{"FROM", "TO", NULL};
@@ -2207,22 +1979,14 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_FROMTO);
 	}
 	/* If we have COPY|BINARY <sth> FROM|TO, complete with filename */
-	else if ((pg_strcasecmp(prev3_wd, "COPY") == 0 ||
-			  pg_strcasecmp(prev3_wd, "\\copy") == 0 ||
-			  pg_strcasecmp(prev3_wd, "BINARY") == 0) &&
-			 (pg_strcasecmp(prev_wd, "FROM") == 0 ||
-			  pg_strcasecmp(prev_wd, "TO") == 0))
+	else if (MATCH("\\?COPY{ BINARY}? #id {FROM|TO}"))
 	{
 		completion_charp = "";
 		matches = completion_matches(text, complete_from_files);
 	}
 
 	/* Handle COPY|BINARY <sth> FROM|TO filename */
-	else if ((pg_strcasecmp(prev4_wd, "COPY") == 0 ||
-			  pg_strcasecmp(prev4_wd, "\\copy") == 0 ||
-			  pg_strcasecmp(prev4_wd, "BINARY") == 0) &&
-			 (pg_strcasecmp(prev2_wd, "FROM") == 0 ||
-			  pg_strcasecmp(prev2_wd, "TO") == 0))
+	else if (MATCH("\\?COPY{ BINARY}? #id {FROM|TO} #nwb"))
 	{
 		static const char *const list_COPY[] =
 		{"BINARY", "OIDS", "DELIMITER", "NULL", "CSV", "ENCODING", NULL};
@@ -2231,9 +1995,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* Handle COPY|BINARY <sth> FROM|TO filename CSV */
-	else if (pg_strcasecmp(prev_wd, "CSV") == 0 &&
-			 (pg_strcasecmp(prev3_wd, "FROM") == 0 ||
-			  pg_strcasecmp(prev3_wd, "TO") == 0))
+	else if (MATCH("{FROM|TO} #nwb CSV"))
 	{
 		static const char *const list_CSV[] =
 		{"HEADER", "QUOTE", "ESCAPE", "FORCE QUOTE", "FORCE NOT NULL", NULL};
@@ -2242,8 +2004,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* CREATE DATABASE */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DATABASE") == 0)
+	else if (MATCH("CREATE DATABASE #id"))
 	{
 		static const char *const list_DATABASE[] =
 		{"OWNER", "TEMPLATE", "ENCODING", "TABLESPACE", "IS_TEMPLATE",
@@ -2253,19 +2014,16 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_DATABASE);
 	}
 
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "DATABASE") == 0 &&
-			 pg_strcasecmp(prev_wd, "TEMPLATE") == 0)
+	else if (MATCH("CREATE DATABASE #id TEMPLATE"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_template_databases, NULL);
 
 	/* CREATE EXTENSION */
 	/* Complete with available extensions rather than installed ones. */
-	else if (pg_strcasecmp(prev2_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev_wd, "EXTENSION") == 0)
+	else if (MATCH("CREATE EXTENSION"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_available_extensions, NULL);
+
 	/* CREATE EXTENSION <name> */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "EXTENSION") == 0)
+	else if (MATCH("CREATE EXTENSION #id"))
 	{
 		static const char *const list_CREATE_EXTENSION[] =
 		{"WITH SCHEMA", "CASCADE", "VERSION", NULL};
@@ -2273,17 +2031,12 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_CREATE_EXTENSION);
 	}
 	/* CREATE EXTENSION <name> VERSION */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "EXTENSION") == 0 &&
-			 pg_strcasecmp(prev_wd, "VERSION") == 0)
-	{
+	else if (MATCH("CREATE EXTENSION [#id] VERSION"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions,
-							prev2_wd);
-	}
+							CAPTURE(1));
 
 	/* CREATE FOREIGN */
-	else if (pg_strcasecmp(prev2_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOREIGN") == 0)
+	else if (MATCH("CREATE FOREIGN"))
 	{
 		static const char *const list_CREATE_FOREIGN[] =
 		{"DATA WRAPPER", "TABLE", NULL};
@@ -2292,10 +2045,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* CREATE FOREIGN DATA WRAPPER */
-	else if (pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev4_wd, "FOREIGN") == 0 &&
-			 pg_strcasecmp(prev3_wd, "DATA") == 0 &&
-			 pg_strcasecmp(prev2_wd, "WRAPPER") == 0)
+	else if (MATCH("CREATE FOREIGN DATA WRAPPER #id"))
 	{
 		static const char *const list_CREATE_FOREIGN_DATA_WRAPPER[] =
 		{"HANDLER", "VALIDATOR", NULL};
@@ -2305,31 +2055,24 @@ psql_completion(const char *text, int start, int end)
 
 	/* CREATE INDEX */
 	/* First off we complete CREATE UNIQUE with "INDEX" */
-	else if (pg_strcasecmp(prev2_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev_wd, "UNIQUE") == 0)
+	else if (MATCH("CREATE UNIQUE"))
 		COMPLETE_WITH_CONST("INDEX");
+
 	/* If we have CREATE|UNIQUE INDEX, then add "ON" and existing indexes */
-	else if (pg_strcasecmp(prev_wd, "INDEX") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "CREATE") == 0 ||
-			  pg_strcasecmp(prev2_wd, "UNIQUE") == 0))
+	else if (MATCH("CREATE {UNIQUE }? INDEX #id"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
 								   " UNION SELECT 'ON'"
 								   " UNION SELECT 'CONCURRENTLY'");
 	/* Complete ... INDEX [<name>] ON with a list of tables  */
-	else if ((pg_strcasecmp(prev3_wd, "INDEX") == 0 ||
-			  pg_strcasecmp(prev2_wd, "INDEX") == 0 ||
-			  pg_strcasecmp(prev2_wd, "CONCURRENTLY") == 0) &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
+	else if (MATCH("INDEX {CONCURRENTLY }? #id ON"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, NULL);
+
 	/* If we have CREATE|UNIQUE INDEX <sth> CONCURRENTLY, then add "ON" */
-	else if ((pg_strcasecmp(prev3_wd, "INDEX") == 0 ||
-			  pg_strcasecmp(prev2_wd, "INDEX") == 0) &&
-			 pg_strcasecmp(prev_wd, "CONCURRENTLY") == 0)
+	else if (MATCH("INDEX #id CONCURRENTLY"))
 		COMPLETE_WITH_CONST("ON");
+
 	/* If we have CREATE|UNIQUE INDEX <sth>, then add "ON" or "CONCURRENTLY" */
-	else if ((pg_strcasecmp(prev3_wd, "CREATE") == 0 ||
-			  pg_strcasecmp(prev3_wd, "UNIQUE") == 0) &&
-			 pg_strcasecmp(prev2_wd, "INDEX") == 0)
+	else if (MATCH("CREATE {UNIQUE }? INDEX #id"))
 	{
 		static const char *const list_CREATE_INDEX[] =
 		{"CONCURRENTLY", "ON", NULL};
@@ -2341,54 +2084,38 @@ psql_completion(const char *text, int start, int end)
 	 * Complete INDEX <name> ON <table> with a list of table columns (which
 	 * should really be in parens)
 	 */
-	else if ((pg_strcasecmp(prev4_wd, "INDEX") == 0 ||
-			  pg_strcasecmp(prev3_wd, "INDEX") == 0 ||
-			  pg_strcasecmp(prev3_wd, "CONCURRENTLY") == 0) &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0)
+	else if (MATCH("INDEX #id {CONCURRENTLY }? ON #id"))
 	{
 		static const char *const list_CREATE_INDEX2[] =
 		{"(", "USING", NULL};
 
 		COMPLETE_WITH_LIST(list_CREATE_INDEX2);
 	}
-	else if ((pg_strcasecmp(prev5_wd, "INDEX") == 0 ||
-			  pg_strcasecmp(prev4_wd, "INDEX") == 0 ||
-			  pg_strcasecmp(prev4_wd, "CONCURRENTLY") == 0) &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "(") == 0)
-		COMPLETE_WITH_ATTR(prev2_wd, "");
+	else if (MATCH("INDEX #id {CONCURRENTLY }? ON [#id]("))
+		COMPLETE_WITH_ATTR(CAPTURE(1), "");
+
 	/* same if you put in USING */
-	else if (pg_strcasecmp(prev5_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev3_wd, "USING") == 0 &&
-			 pg_strcasecmp(prev_wd, "(") == 0)
-		COMPLETE_WITH_ATTR(prev4_wd, "");
+	else if (MATCH("ON [#id] USING #id("))
+		COMPLETE_WITH_ATTR(CAPTURE(1), "");
+
 	/* Complete USING with an index method */
-	else if ((pg_strcasecmp(prev6_wd, "INDEX") == 0 ||
-			  pg_strcasecmp(prev5_wd, "INDEX") == 0 ||
-			  pg_strcasecmp(prev4_wd, "INDEX") == 0) &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "USING") == 0)
+	else if (MATCH("INDEX #id {#nwb }* ON #id USING"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_access_methods, NULL);
-	else if (pg_strcasecmp(prev4_wd, "ON") == 0 &&
-			 (!(pg_strcasecmp(prev6_wd, "POLICY") == 0) &&
-			  !(pg_strcasecmp(prev4_wd, "FOR") == 0)) &&
-			 pg_strcasecmp(prev2_wd, "USING") == 0)
+
+	else if (MATCH("^{!POLICY|FOR }+ON #id USING #id"))
 		COMPLETE_WITH_CONST("(");
 
 	/* CREATE POLICY */
 	/* Complete "CREATE POLICY <name> ON" */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "POLICY") == 0)
+	else if (MATCH("CREATE POLICY #id"))
 		COMPLETE_WITH_CONST("ON");
+
 	/* Complete "CREATE POLICY <name> ON <table>" */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
+	else if (MATCH("CREATE POLICY #id ON"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+
 	/* Complete "CREATE POLICY <name> ON <table> FOR|TO|USING|WITH CHECK" */
-	else if (pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev4_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0)
+	else if (MATCH("CREATE POLICY #id ON #id"))
 	{
 		static const char *const list_POLICYOPTIONS[] =
 		{"FOR", "TO", "USING", "WITH CHECK", NULL};
@@ -2400,10 +2127,7 @@ psql_completion(const char *text, int start, int end)
 	 * Complete "CREATE POLICY <name> ON <table> FOR
 	 * ALL|SELECT|INSERT|UPDATE|DELETE"
 	 */
-	else if (pg_strcasecmp(prev6_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev5_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOR") == 0)
+	else if (MATCH("CREATE POLICY #id ON #id FOR"))
 	{
 		static const char *const list_POLICYCMDS[] =
 		{"ALL", "SELECT", "INSERT", "UPDATE", "DELETE", NULL};
@@ -2411,10 +2135,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_POLICYCMDS);
 	}
 	/* Complete "CREATE POLICY <name> ON <table> FOR INSERT TO|WITH CHECK" */
-	else if (pg_strcasecmp(prev6_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev4_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev2_wd, "FOR") == 0 &&
-			 pg_strcasecmp(prev_wd, "INSERT") == 0)
+	else if (MATCH("CREATE POLICY #id ON #id FOR INSERT"))
 	{
 		static const char *const list_POLICYOPTIONS[] =
 		{"TO", "WITH CHECK", NULL};
@@ -2426,11 +2147,7 @@ psql_completion(const char *text, int start, int end)
 	 * Complete "CREATE POLICY <name> ON <table> FOR SELECT TO|USING" Complete
 	 * "CREATE POLICY <name> ON <table> FOR DELETE TO|USING"
 	 */
-	else if (pg_strcasecmp(prev6_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev4_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev2_wd, "FOR") == 0 &&
-			 (pg_strcasecmp(prev_wd, "SELECT") == 0 ||
-			  pg_strcasecmp(prev_wd, "DELETE") == 0))
+	else if (MATCH("CREATE POLICY #id ON #id FOR {SELECT|DELETE}"))
 	{
 		static const char *const list_POLICYOPTIONS[] =
 		{"TO", "USING", NULL};
@@ -2443,11 +2160,7 @@ psql_completion(const char *text, int start, int end)
 	 * Complete "CREATE POLICY <name> ON <table> FOR UPDATE TO|USING|WITH
 	 * CHECK"
 	 */
-	else if (pg_strcasecmp(prev6_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev4_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev2_wd, "FOR") == 0 &&
-			 (pg_strcasecmp(prev_wd, "ALL") == 0 ||
-			  pg_strcasecmp(prev_wd, "UPDATE") == 0))
+	else if (MATCH("CREATE POLICY #id ON #id FOR {ALL|UPDATE}"))
 	{
 		static const char *const list_POLICYOPTIONS[] =
 		{"TO", "USING", "WITH CHECK", NULL};
@@ -2455,32 +2168,24 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_POLICYOPTIONS);
 	}
 	/* Complete "CREATE POLICY <name> ON <table> TO <role>" */
-	else if (pg_strcasecmp(prev6_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev5_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "TO") == 0)
+	else if (MATCH("CREATE POLICY #id ON #id TO"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles, NULL);
+
 	/* Complete "CREATE POLICY <name> ON <table> USING (" */
-	else if (pg_strcasecmp(prev6_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev5_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "USING") == 0)
+	else if (MATCH("CREATE POLICY #id ON #id USING"))
 		COMPLETE_WITH_CONST("(");
 
 /* CREATE RULE */
 	/* Complete "CREATE RULE <sth>" with "AS" */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "RULE") == 0)
+	else if (MATCH("CREATE RULE #id"))
 		COMPLETE_WITH_CONST("AS");
+
 	/* Complete "CREATE RULE <sth> AS with "ON" */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "RULE") == 0 &&
-			 pg_strcasecmp(prev_wd, "AS") == 0)
+	else if (MATCH("CREATE RULE #id AS"))
 		COMPLETE_WITH_CONST("ON");
+
 	/* Complete "RULE * AS ON" with SELECT|UPDATE|DELETE|INSERT */
-	else if (pg_strcasecmp(prev4_wd, "RULE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "AS") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
+	else if (MATCH("RULE #id AS ON"))
 	{
 		static const char *const rule_events[] =
 		{"SELECT", "UPDATE", "INSERT", "DELETE", NULL};
@@ -2488,24 +2193,15 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(rule_events);
 	}
 	/* Complete "AS ON <sth with a 'T' :)>" with a "TO" */
-	else if (pg_strcasecmp(prev3_wd, "AS") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0 &&
-			 (pg_toupper((unsigned char) prev_wd[4]) == 'T' ||
-			  pg_toupper((unsigned char) prev_wd[5]) == 'T'))
+	else if (MATCH("AS ON {SELECT|UPDATE|INSERT|DELETE}"))
 		COMPLETE_WITH_CONST("TO");
+
 	/* Complete "AS ON <sth> TO" with a table name */
-	else if (pg_strcasecmp(prev4_wd, "AS") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "TO") == 0)
+	else if (MATCH("AS ON #kwd TO"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
 
 /* CREATE TEMP/TEMPORARY SEQUENCE <name> */
-	else if ((pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			  pg_strcasecmp(prev2_wd, "SEQUENCE") == 0) ||
-			 (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			  (pg_strcasecmp(prev3_wd, "TEMP") == 0 ||
-			   pg_strcasecmp(prev3_wd, "TEMPORARY") == 0) &&
-			  pg_strcasecmp(prev2_wd, "SEQUENCE") == 0))
+	else if (MATCH("CREATE {TEMP{ORARY}? }? SEQUENCE #id"))
 	{
 		static const char *const list_CREATESEQUENCE[] =
 		{"INCREMENT BY", "MINVALUE", "MAXVALUE", "NO", "CACHE",
@@ -2514,13 +2210,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_CREATESEQUENCE);
 	}
 /* CREATE TEMP/TEMPORARY SEQUENCE <name> NO */
-	else if (((pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			  pg_strcasecmp(prev3_wd, "SEQUENCE") == 0) ||
-			 (pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
-			  (pg_strcasecmp(prev4_wd, "TEMP") == 0 ||
-			   pg_strcasecmp(prev4_wd, "TEMPORARY") == 0) &&
-			  pg_strcasecmp(prev3_wd, "SEQUENCE") == 0)) &&
-			 pg_strcasecmp(prev_wd, "NO") == 0)
+	else if (MATCH("CREATE {TEMP{ORARY}? }? SEQUENCE #id NO"))
 	{
 		static const char *const list_CREATESEQUENCE2[] =
 		{"MINVALUE", "MAXVALUE", "CYCLE", NULL};
@@ -2529,8 +2219,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 /* CREATE SERVER <name> */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SERVER") == 0)
+	else if (MATCH("CREATE SERVER #id"))
 	{
 		static const char *const list_CREATE_SERVER[] =
 		{"TYPE", "VERSION", "FOREIGN DATA WRAPPER", NULL};
@@ -2540,9 +2229,7 @@ psql_completion(const char *text, int start, int end)
 
 /* CREATE TABLE */
 	/* Complete "CREATE TEMP/TEMPORARY" with the possible temp objects */
-	else if (pg_strcasecmp(prev2_wd, "CREATE") == 0 &&
-			 (pg_strcasecmp(prev_wd, "TEMP") == 0 ||
-			  pg_strcasecmp(prev_wd, "TEMPORARY") == 0))
+	else if (MATCH("CREATE {TEMP{ORARY}?}"))
 	{
 		static const char *const list_TEMP[] =
 		{"SEQUENCE", "TABLE", "VIEW", NULL};
@@ -2550,8 +2237,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_TEMP);
 	}
 	/* Complete "CREATE UNLOGGED" with TABLE */
-	else if (pg_strcasecmp(prev2_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev_wd, "UNLOGGED") == 0)
+	else if (MATCH("CREATE UNLOGGED"))
 	{
 		static const char *const list_UNLOGGED[] =
 		{"TABLE", "MATERIALIZED VIEW", NULL};
@@ -2560,8 +2246,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 /* CREATE TABLESPACE */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TABLESPACE") == 0)
+	else if (MATCH("CREATE TABLESPACE #id"))
 	{
 		static const char *const list_CREATETABLESPACE[] =
 		{"OWNER", "LOCATION", NULL};
@@ -2569,32 +2254,23 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_CREATETABLESPACE);
 	}
 	/* Complete CREATE TABLESPACE name OWNER name with "LOCATION" */
-	else if (pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TABLESPACE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "OWNER") == 0)
-	{
+	else if (MATCH("CREATE TABLESPACE #id OWNER"))
 		COMPLETE_WITH_CONST("LOCATION");
-	}
 
 /* CREATE TEXT SEARCH */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TEXT") == 0 &&
-			 pg_strcasecmp(prev_wd, "SEARCH") == 0)
+	else if (MATCH("CREATE TEXT SEARCH"))
 	{
 		static const char *const list_CREATETEXTSEARCH[] =
 		{"CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE", NULL};
 
 		COMPLETE_WITH_LIST(list_CREATETEXTSEARCH);
 	}
-	else if (pg_strcasecmp(prev4_wd, "TEXT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "SEARCH") == 0 &&
-			 pg_strcasecmp(prev2_wd, "CONFIGURATION") == 0)
+	else if (MATCH("TEXT SEARCH CONFIGURATION #id"))
 		COMPLETE_WITH_CONST("(");
 
 /* CREATE TRIGGER */
 	/* complete CREATE TRIGGER <name> with BEFORE,AFTER */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TRIGGER") == 0)
+	else if (MATCH("CREATE TRIGGER #id"))
 	{
 		static const char *const list_CREATETRIGGER[] =
 		{"BEFORE", "AFTER", "INSTEAD OF", NULL};
@@ -2602,10 +2278,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_CREATETRIGGER);
 	}
 	/* complete CREATE TRIGGER <name> BEFORE,AFTER with an event */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TRIGGER") == 0 &&
-			 (pg_strcasecmp(prev_wd, "BEFORE") == 0 ||
-			  pg_strcasecmp(prev_wd, "AFTER") == 0))
+	else if (MATCH("CREATE TRIGGER #id {BEFORE|AFTER}"))
 	{
 		static const char *const list_CREATETRIGGER_EVENTS[] =
 		{"INSERT", "DELETE", "UPDATE", "TRUNCATE", NULL};
@@ -2613,10 +2286,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_CREATETRIGGER_EVENTS);
 	}
 	/* complete CREATE TRIGGER <name> INSTEAD OF with an event */
-	else if (pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TRIGGER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "INSTEAD") == 0 &&
-			 pg_strcasecmp(prev_wd, "OF") == 0)
+	else if (MATCH("CREATE TRIGGER #id INSTEAD OF"))
 	{
 		static const char *const list_CREATETRIGGER_EVENTS[] =
 		{"INSERT", "DELETE", "UPDATE", NULL};
@@ -2624,13 +2294,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_CREATETRIGGER_EVENTS);
 	}
 	/* complete CREATE TRIGGER <name> BEFORE,AFTER sth with OR,ON */
-	else if ((pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
-			  pg_strcasecmp(prev4_wd, "TRIGGER") == 0 &&
-			  (pg_strcasecmp(prev2_wd, "BEFORE") == 0 ||
-			   pg_strcasecmp(prev2_wd, "AFTER") == 0)) ||
-			 (pg_strcasecmp(prev5_wd, "TRIGGER") == 0 &&
-			  pg_strcasecmp(prev3_wd, "INSTEAD") == 0 &&
-			  pg_strcasecmp(prev2_wd, "OF") == 0))
+	else if (MATCH("CREATE TRIGGER #id {BEFORE|AFTER|INSTEAD_OF} #kwd"))
 	{
 		static const char *const list_CREATETRIGGER2[] =
 		{"ON", "OR", NULL};
@@ -2642,27 +2306,19 @@ psql_completion(const char *text, int start, int end)
 	 * complete CREATE TRIGGER <name> BEFORE,AFTER event ON with a list of
 	 * tables
 	 */
-	else if (pg_strcasecmp(prev5_wd, "TRIGGER") == 0 &&
-			 (pg_strcasecmp(prev3_wd, "BEFORE") == 0 ||
-			  pg_strcasecmp(prev3_wd, "AFTER") == 0) &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
+	else if (MATCH("TRIGGER #id {BEFORE|AFTER} #kwd ON"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+
 	/* complete CREATE TRIGGER ... INSTEAD OF event ON with a list of views */
-	else if (pg_strcasecmp(prev4_wd, "INSTEAD") == 0 &&
-			 pg_strcasecmp(prev3_wd, "OF") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
+	else if (MATCH("INSTEAD OF #kwd ON"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
+
 	/* complete CREATE TRIGGER ... EXECUTE with PROCEDURE */
-	else if (pg_strcasecmp(prev_wd, "EXECUTE") == 0 &&
-			 !(pg_strcasecmp(prev2_wd, "GRANT") == 0 && prev3_wd[0] == '\0') &&
-			 prev2_wd[0] != '\0')
+	else if (MATCH("CREATE TRIGGER {#nwb }+ EXECUTE"))
 		COMPLETE_WITH_CONST("PROCEDURE");
 
 /* CREATE ROLE,USER,GROUP <name> */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 !(pg_strcasecmp(prev2_wd, "USER") == 0 && pg_strcasecmp(prev_wd, "MAPPING") == 0) &&
-			 (pg_strcasecmp(prev2_wd, "ROLE") == 0 ||
-			  pg_strcasecmp(prev2_wd, "GROUP") == 0 || pg_strcasecmp(prev2_wd, "USER") == 0))
+	else if (MATCH("CREATE {{USER !MAPPING_}|ROLE |GROUP } #id"))
 	{
 		static const char *const list_CREATEROLE[] =
 		{"ADMIN", "BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
@@ -2676,11 +2332,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 /* CREATE ROLE,USER,GROUP <name> WITH */
-	else if ((pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			  (pg_strcasecmp(prev3_wd, "ROLE") == 0 ||
-			   pg_strcasecmp(prev3_wd, "GROUP") == 0 ||
-			   pg_strcasecmp(prev3_wd, "USER") == 0) &&
-			  pg_strcasecmp(prev_wd, "WITH") == 0))
+	else if (MATCH("CREATE {ROLE|GROUP|USER} #id WITH"))
 	{
 		/* Similar to the above, but don't complete "WITH" again. */
 		static const char *const list_CREATEROLE_WITH[] =
@@ -2698,18 +2350,11 @@ psql_completion(const char *text, int start, int end)
 	 * complete CREATE ROLE,USER,GROUP <name> ENCRYPTED,UNENCRYPTED with
 	 * PASSWORD
 	 */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 (pg_strcasecmp(prev3_wd, "ROLE") == 0 ||
-			  pg_strcasecmp(prev3_wd, "GROUP") == 0 || pg_strcasecmp(prev3_wd, "USER") == 0) &&
-			 (pg_strcasecmp(prev_wd, "ENCRYPTED") == 0 || pg_strcasecmp(prev_wd, "UNENCRYPTED") == 0))
-	{
+	else if (MATCH("CREATE {ROLE|GROUP|USER} #id {UN}?ENCRYPTED"))
 		COMPLETE_WITH_CONST("PASSWORD");
-	}
+
 	/* complete CREATE ROLE,USER,GROUP <name> IN with ROLE,GROUP */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 (pg_strcasecmp(prev3_wd, "ROLE") == 0 ||
-			  pg_strcasecmp(prev3_wd, "GROUP") == 0 || pg_strcasecmp(prev3_wd, "USER") == 0) &&
-			 pg_strcasecmp(prev_wd, "IN") == 0)
+	else if (MATCH("CREATE {ROLE|GROUP|USER} #id IN"))
 	{
 		static const char *const list_CREATEROLE3[] =
 		{"GROUP", "ROLE", NULL};
@@ -2719,45 +2364,35 @@ psql_completion(const char *text, int start, int end)
 
 /* CREATE VIEW */
 	/* Complete CREATE VIEW <name> with AS */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "VIEW") == 0)
+	else if (MATCH("CREATE VIEW #id"))
 		COMPLETE_WITH_CONST("AS");
+
 	/* Complete "CREATE VIEW <sth> AS with "SELECT" */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "VIEW") == 0 &&
-			 pg_strcasecmp(prev_wd, "AS") == 0)
+	else if (MATCH("CREATE VIEW #id AS"))
 		COMPLETE_WITH_CONST("SELECT");
 
 /* CREATE MATERIALIZED VIEW */
-	else if (pg_strcasecmp(prev2_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev_wd, "MATERIALIZED") == 0)
+	else if (MATCH("CREATE MATERIALIZED"))
 		COMPLETE_WITH_CONST("VIEW");
+
 	/* Complete CREATE MATERIALIZED VIEW <name> with AS */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev2_wd, "VIEW") == 0)
+	else if (MATCH("CREATE MATERIALIZED VIEW #id"))
 		COMPLETE_WITH_CONST("AS");
+
 	/* Complete "CREATE MATERIALIZED VIEW <sth> AS with "SELECT" */
-	else if (pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev4_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev3_wd, "VIEW") == 0 &&
-			 pg_strcasecmp(prev_wd, "AS") == 0)
+	else if (MATCH("CREATE MATERIALIZED VIEW #id AS"))
 		COMPLETE_WITH_CONST("SELECT");
 
 /* CREATE EVENT TRIGGER */
-	else if (pg_strcasecmp(prev2_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev_wd, "EVENT") == 0)
+	else if (MATCH("CREATE EVENT"))
 		COMPLETE_WITH_CONST("TRIGGER");
+
 	/* Complete CREATE EVENT TRIGGER <name> with ON */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "EVENT") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TRIGGER") == 0)
+	else if (MATCH("CREATE EVENT TRIGGER #id"))
 		COMPLETE_WITH_CONST("ON");
+
 	/* Complete CREATE EVENT TRIGGER <name> ON with event_type */
-	else if (pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev4_wd, "EVENT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TRIGGER") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
+	else if (MATCH("CREATE EVENT TRIGGER #id ON"))
 	{
 		static const char *const list_CREATE_EVENT_TRIGGER_ON[] =
 		{"ddl_command_start", "ddl_command_end", "sql_drop", NULL};
@@ -2766,7 +2401,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 /* DECLARE */
-	else if (pg_strcasecmp(prev2_wd, "DECLARE") == 0)
+	else if (MATCH("DECLARE #id"))
 	{
 		static const char *const list_DECLARE[] =
 		{"BINARY", "INSENSITIVE", "SCROLL", "NO SCROLL", "CURSOR", NULL};
@@ -2775,7 +2410,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 /* CURSOR */
-	else if (pg_strcasecmp(prev_wd, "CURSOR") == 0)
+	else if (MATCH("CURSOR"))
 	{
 		static const char *const list_DECLARECURSOR[] =
 		{"WITH HOLD", "WITHOUT HOLD", "FOR", NULL};
@@ -2790,19 +2425,15 @@ psql_completion(const char *text, int start, int end)
 	 * Complete DELETE with FROM (only if the word before that is not "ON"
 	 * (cf. rules) or "BEFORE" or "AFTER" (cf. triggers) or GRANT)
 	 */
-	else if (pg_strcasecmp(prev_wd, "DELETE") == 0 &&
-			 !(pg_strcasecmp(prev2_wd, "ON") == 0 ||
-			   pg_strcasecmp(prev2_wd, "GRANT") == 0 ||
-			   pg_strcasecmp(prev2_wd, "BEFORE") == 0 ||
-			   pg_strcasecmp(prev2_wd, "AFTER") == 0))
+	else if (MATCH("DELETE"))
 		COMPLETE_WITH_CONST("FROM");
+
 	/* Complete DELETE FROM with a list of tables */
-	else if (pg_strcasecmp(prev2_wd, "DELETE") == 0 &&
-			 pg_strcasecmp(prev_wd, "FROM") == 0)
+	else if (MATCH("DELETE FROM"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables, NULL);
+
 	/* Complete DELETE FROM <table> */
-	else if (pg_strcasecmp(prev3_wd, "DELETE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "FROM") == 0)
+	else if (MATCH("DELETE FROM #id"))
 	{
 		static const char *const list_DELETE[] =
 		{"USING", "WHERE", "SET", NULL};
@@ -2812,7 +2443,7 @@ psql_completion(const char *text, int start, int end)
 	/* XXX: implement tab completion for DELETE ... USING */
 
 /* DISCARD */
-	else if (pg_strcasecmp(prev_wd, "DISCARD") == 0)
+	else if (MATCH("DISCARD"))
 	{
 		static const char *const list_DISCARD[] =
 		{"ALL", "PLANS", "SEQUENCES", "TEMP", NULL};
@@ -2825,7 +2456,7 @@ psql_completion(const char *text, int start, int end)
 	/*
 	 * Complete DO with LANGUAGE.
 	 */
-	else if (pg_strcasecmp(prev_wd, "DO") == 0)
+	else if (MATCH("DO"))
 	{
 		static const char *const list_DO[] =
 		{"LANGUAGE", NULL};
@@ -2835,46 +2466,13 @@ psql_completion(const char *text, int start, int end)
 
 /* DROP (when not the previous word) */
 	/* DROP AGGREGATE */
-	else if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev2_wd, "AGGREGATE") == 0)
+	else if (MATCH("DROP AGGREGATE #id"))
 		COMPLETE_WITH_CONST("(");
 
 	/* DROP object with CASCADE / RESTRICT */
-	else if ((pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			  (pg_strcasecmp(prev2_wd, "COLLATION") == 0 ||
-			   pg_strcasecmp(prev2_wd, "CONVERSION") == 0 ||
-			   pg_strcasecmp(prev2_wd, "DOMAIN") == 0 ||
-			   pg_strcasecmp(prev2_wd, "EXTENSION") == 0 ||
-			   pg_strcasecmp(prev2_wd, "FUNCTION") == 0 ||
-			   pg_strcasecmp(prev2_wd, "INDEX") == 0 ||
-			   pg_strcasecmp(prev2_wd, "LANGUAGE") == 0 ||
-			   pg_strcasecmp(prev2_wd, "SCHEMA") == 0 ||
-			   pg_strcasecmp(prev2_wd, "SEQUENCE") == 0 ||
-			   pg_strcasecmp(prev2_wd, "SERVER") == 0 ||
-			   pg_strcasecmp(prev2_wd, "TABLE") == 0 ||
-			   pg_strcasecmp(prev2_wd, "TYPE") == 0 ||
-			   pg_strcasecmp(prev2_wd, "VIEW") == 0)) ||
-			 (pg_strcasecmp(prev4_wd, "DROP") == 0 &&
-			  pg_strcasecmp(prev3_wd, "AGGREGATE") == 0 &&
-			  prev_wd[strlen(prev_wd) - 1] == ')') ||
-			 (pg_strcasecmp(prev4_wd, "DROP") == 0 &&
-			  pg_strcasecmp(prev3_wd, "EVENT") == 0 &&
-			  pg_strcasecmp(prev2_wd, "TRIGGER") == 0) ||
-			 (pg_strcasecmp(prev5_wd, "DROP") == 0 &&
-			  pg_strcasecmp(prev4_wd, "FOREIGN") == 0 &&
-			  pg_strcasecmp(prev3_wd, "DATA") == 0 &&
-			  pg_strcasecmp(prev2_wd, "WRAPPER") == 0) ||
-			 (pg_strcasecmp(prev5_wd, "DROP") == 0 &&
-			  pg_strcasecmp(prev4_wd, "TEXT") == 0 &&
-			  pg_strcasecmp(prev3_wd, "SEARCH") == 0 &&
-			  (pg_strcasecmp(prev2_wd, "CONFIGURATION") == 0 ||
-			   pg_strcasecmp(prev2_wd, "DICTIONARY") == 0 ||
-			   pg_strcasecmp(prev2_wd, "PARSER") == 0 ||
-			   pg_strcasecmp(prev2_wd, "TEMPLATE") == 0))
-		)
-	{
-		if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			pg_strcasecmp(prev2_wd, "FUNCTION") == 0)
+	else if (MATCH("DROP {{{COLLATION|CONVERSION|DOMAIN|EXTENSION|[FUNCTION]|INDEX|LANGUAGE|SCHEMA|SEQUENCE|SERVER|TABLE|TYPE|VIEW|{EVENT TRIGGER}|{FOREGN DATA WRAPPER}|{TEXT SEARCH {CONFIGURATION|DICTIONARY|PARSER|TEMPLATE}}} #id }|{AGGREGATE #id(..)}}"))
+	{
+		if (pg_strcasecmp(CAPTURE(1), "FUNCTION") == 0)
 		{
 			COMPLETE_WITH_CONST("(");
 		}
@@ -2886,8 +2484,7 @@ psql_completion(const char *text, int start, int end)
 			COMPLETE_WITH_LIST(list_DROPCR);
 		}
 	}
-	else if (pg_strcasecmp(prev2_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOREIGN") == 0)
+	else if (MATCH("DROP FOREIGN"))
 	{
 		static const char *const drop_CREATE_FOREIGN[] =
 		{"DATA WRAPPER", "TABLE", NULL};
@@ -2896,34 +2493,22 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* DROP MATERIALIZED VIEW */
-	else if (pg_strcasecmp(prev2_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev_wd, "MATERIALIZED") == 0)
-	{
+	else if (MATCH("DROP MATERIALIZED"))
 		COMPLETE_WITH_CONST("VIEW");
-	}
-	else if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev2_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev_wd, "VIEW") == 0)
-	{
+
+	else if (MATCH("DROP MATERIALIZED VIEW"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
-	}
 
-	else if (pg_strcasecmp(prev4_wd, "DROP") == 0 &&
-			 (pg_strcasecmp(prev3_wd, "AGGREGATE") == 0 ||
-			  pg_strcasecmp(prev3_wd, "FUNCTION") == 0) &&
-			 pg_strcasecmp(prev_wd, "(") == 0)
-		COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
+	else if (MATCH("DROP {AGGREGATE|FUNCTION} [#id]("))
+		COMPLETE_WITH_FUNCTION_ARG(CAPTURE(1));
+
 	/* DROP OWNED BY */
-	else if (pg_strcasecmp(prev2_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev_wd, "OWNED") == 0)
+	else if (MATCH("DROP OWNED"))
 		COMPLETE_WITH_CONST("BY");
-	else if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev2_wd, "OWNED") == 0 &&
-			 pg_strcasecmp(prev_wd, "BY") == 0)
+	else if (MATCH("DROP OWNED BY"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
-	else if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TEXT") == 0 &&
-			 pg_strcasecmp(prev_wd, "SEARCH") == 0)
+
+	else if (MATCH("DROP TEXT SEARCH"))
 	{
 
 		static const char *const list_ALTERTEXTSEARCH[] =
@@ -2933,20 +2518,11 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* DROP TRIGGER */
-	else if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev2_wd, "TRIGGER") == 0)
-	{
+	else if (MATCH("DROP TRIGGER #id"))
 		COMPLETE_WITH_CONST("ON");
-	}
-	else if (pg_strcasecmp(prev4_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev3_wd, "TRIGGER") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger, prev2_wd);
-	}
-	else if (pg_strcasecmp(prev5_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev4_wd, "TRIGGER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0)
+	else if (MATCH("DROP TRIGGER [#id] ON"))
+		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger, CAPTURE(1));
+	else if (MATCH("DROP TRIGGER #id ON #id"))
 	{
 		static const char *const list_DROPCR[] =
 		{"CASCADE", "RESTRICT", NULL};
@@ -2955,53 +2531,32 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* DROP EVENT TRIGGER */
-	else if (pg_strcasecmp(prev2_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev_wd, "EVENT") == 0)
-	{
+	else if (MATCH("DROP EVENT"))
 		COMPLETE_WITH_CONST("TRIGGER");
-	}
-	else if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev2_wd, "EVENT") == 0 &&
-			 pg_strcasecmp(prev_wd, "TRIGGER") == 0)
-	{
+
+	else if (MATCH("DROP_EVENT TRIGGER"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers, NULL);
-	}
 
 	/* DROP POLICY <name>  */
-	else if (pg_strcasecmp(prev2_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev_wd, "POLICY") == 0)
-	{
+	else if (MATCH("DROP POLICY"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_policies, NULL);
-	}
+
 	/* DROP POLICY <name> ON */
-	else if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev2_wd, "POLICY") == 0)
-	{
+	else if (MATCH("DROP POLICY #id"))
 		COMPLETE_WITH_CONST("ON");
-	}
+
 	/* DROP POLICY <name> ON <table> */
-	else if (pg_strcasecmp(prev4_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev3_wd, "POLICY") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_policy, prev2_wd);
-	}
+	else if (MATCH("DROP POLICY [#id] ON"))
+		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_policy, CAPTURE(1));
 
 	/* DROP RULE */
-	else if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev2_wd, "RULE") == 0)
-	{
+	else if (MATCH("DROP RULE #id"))
 		COMPLETE_WITH_CONST("ON");
-	}
-	else if (pg_strcasecmp(prev4_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev3_wd, "RULE") == 0 &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
-	{
-		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_rule, prev2_wd);
-	}
-	else if (pg_strcasecmp(prev5_wd, "DROP") == 0 &&
-			 pg_strcasecmp(prev4_wd, "RULE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0)
+
+	else if (MATCH("DROP RULE [#id] ON"))
+		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_rule, CAPTURE(1));
+
+	else if (MATCH("DROP RULE #id ON #id"))
 	{
 		static const char *const list_DROPCR[] =
 		{"CASCADE", "RESTRICT", NULL};
@@ -3010,8 +2565,7 @@ psql_completion(const char *text, int start, int end)
 	}
 
 /* EXECUTE, but not EXECUTE embedded in other commands */
-	else if (pg_strcasecmp(prev_wd, "EXECUTE") == 0 &&
-			 prev2_wd[0] == '\0')
+	else if (MATCH("^EXECUTE"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_prepared_statements, NULL);
 
 /* EXPLAIN */
@@ -3019,26 +2573,21 @@ psql_completion(const char *text, int start, int end)
 	/*
 	 * Complete EXPLAIN [ANALYZE] [VERBOSE] with list of EXPLAIN-able commands
 	 */
-	else if (pg_strcasecmp(prev_wd, "EXPLAIN") == 0)
+	else if (MATCH("EXPLAIN"))
 	{
 		static const char *const list_EXPLAIN[] =
 		{"SELECT", "INSERT", "DELETE", "UPDATE", "DECLARE", "ANALYZE", "VERBOSE", NULL};
 
 		COMPLETE_WITH_LIST(list_EXPLAIN);
 	}
-	else if (pg_strcasecmp(prev2_wd, "EXPLAIN") == 0 &&
-			 pg_strcasecmp(prev_wd, "ANALYZE") == 0)
+	else if (MATCH("EXPLAIN ANALYZE"))
 	{
 		static const char *const list_EXPLAIN[] =
 		{"SELECT", "INSERT", "DELETE", "UPDATE", "DECLARE", "VERBOSE", NULL};
 
 		COMPLETE_WITH_LIST(list_EXPLAIN);
 	}
-	else if ((pg_strcasecmp(prev2_wd, "EXPLAIN") == 0 &&
-			  pg_strcasecmp(prev_wd, "VERBOSE") == 0) ||
-			 (pg_strcasecmp(prev3_wd, "EXPLAIN") == 0 &&
-			  pg_strcasecmp(prev2_wd, "ANALYZE") == 0 &&
-			  pg_strcasecmp(prev_wd, "VERBOSE") == 0))
+	else if (MATCH("EXPLAIN{ ANALYZE}? VERBOSE"))
 	{
 		static const char *const list_EXPLAIN[] =
 		{"SELECT", "INSERT", "DELETE", "UPDATE", "DECLARE", NULL};
@@ -3048,8 +2597,7 @@ psql_completion(const char *text, int start, int end)
 
 /* FETCH && MOVE */
 	/* Complete FETCH with one of FORWARD, BACKWARD, RELATIVE */
-	else if (pg_strcasecmp(prev_wd, "FETCH") == 0 ||
-			 pg_strcasecmp(prev_wd, "MOVE") == 0)
+	else if (MATCH("{FETCH|MOVE}"))
 	{
 		static const char *const list_FETCH1[] =
 		{"ABSOLUTE", "BACKWARD", "FORWARD", "RELATIVE", NULL};
@@ -3057,8 +2605,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_FETCH1);
 	}
 	/* Complete FETCH <sth> with one of ALL, NEXT, PRIOR */
-	else if (pg_strcasecmp(prev2_wd, "FETCH") == 0 ||
-			 pg_strcasecmp(prev2_wd, "MOVE") == 0)
+	else if (MATCH("{FETCH|MOVE} #id"))
 	{
 		static const char *const list_FETCH2[] =
 		{"ALL", "NEXT", "PRIOR", NULL};
@@ -3071,8 +2618,7 @@ psql_completion(const char *text, int start, int end)
 	 * but we may as well tab-complete both: perhaps some users prefer one
 	 * variant or the other.
 	 */
-	else if (pg_strcasecmp(prev3_wd, "FETCH") == 0 ||
-			 pg_strcasecmp(prev3_wd, "MOVE") == 0)
+	else if (MATCH("{FETCH|MOVE} #id #id"))
 	{
 		static const char *const list_FROMIN[] =
 		{"FROM", "IN", NULL};
@@ -3082,27 +2628,20 @@ psql_completion(const char *text, int start, int end)
 
 /* FOREIGN DATA WRAPPER */
 	/* applies in ALTER/DROP FDW and in CREATE SERVER */
-	else if (pg_strcasecmp(prev4_wd, "CREATE") != 0 &&
-			 pg_strcasecmp(prev3_wd, "FOREIGN") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DATA") == 0 &&
-			 pg_strcasecmp(prev_wd, "WRAPPER") == 0)
+	else if (MATCH("{ALTER|DROP} FOREIGN DATA WRAPPER"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_fdws, NULL);
 
 /* FOREIGN TABLE */
-	else if (pg_strcasecmp(prev3_wd, "CREATE") != 0 &&
-			 pg_strcasecmp(prev2_wd, "FOREIGN") == 0 &&
-			 pg_strcasecmp(prev_wd, "TABLE") == 0)
+	else if (MATCH("CREATE FOREIGN TABLE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables, NULL);
 
 /* FOREIGN SERVER */
-	else if (pg_strcasecmp(prev2_wd, "FOREIGN") == 0 &&
-			 pg_strcasecmp(prev_wd, "SERVER") == 0)
+	else if (MATCH("FOREIGN SERVER"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_servers, NULL);
 
 /* GRANT && REVOKE */
 	/* Complete GRANT/REVOKE with a list of roles and privileges */
-	else if (pg_strcasecmp(prev_wd, "GRANT") == 0 ||
-			 pg_strcasecmp(prev_wd, "REVOKE") == 0)
+	else if (MATCH("{GRANT|REVOKE}"))
 	{
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles
 							" UNION SELECT 'SELECT'"
@@ -3125,32 +2664,12 @@ psql_completion(const char *text, int start, int end)
 	 * Complete GRANT/REVOKE <privilege> with "ON", GRANT/REVOKE <role> with
 	 * TO/FROM
 	 */
-	else if (pg_strcasecmp(prev2_wd, "GRANT") == 0 ||
-			 pg_strcasecmp(prev2_wd, "REVOKE") == 0)
-	{
-		if (pg_strcasecmp(prev_wd, "SELECT") == 0
-			|| pg_strcasecmp(prev_wd, "INSERT") == 0
-			|| pg_strcasecmp(prev_wd, "UPDATE") == 0
-			|| pg_strcasecmp(prev_wd, "DELETE") == 0
-			|| pg_strcasecmp(prev_wd, "TRUNCATE") == 0
-			|| pg_strcasecmp(prev_wd, "REFERENCES") == 0
-			|| pg_strcasecmp(prev_wd, "TRIGGER") == 0
-			|| pg_strcasecmp(prev_wd, "CREATE") == 0
-			|| pg_strcasecmp(prev_wd, "CONNECT") == 0
-			|| pg_strcasecmp(prev_wd, "TEMPORARY") == 0
-			|| pg_strcasecmp(prev_wd, "TEMP") == 0
-			|| pg_strcasecmp(prev_wd, "EXECUTE") == 0
-			|| pg_strcasecmp(prev_wd, "USAGE") == 0
-			|| pg_strcasecmp(prev_wd, "ALL") == 0)
+	else if (MATCH("{GRANT|REVOKE} {SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|CREATE|CONNECT|TEMP{ORARY}?|EXECUTE|USAGE|ALL}"))
 			COMPLETE_WITH_CONST("ON");
-		else
-		{
-			if (pg_strcasecmp(prev2_wd, "GRANT") == 0)
-				COMPLETE_WITH_CONST("TO");
-			else
-				COMPLETE_WITH_CONST("FROM");
-		}
-	}
+	else if (MATCH("GRANT #id"))
+		COMPLETE_WITH_CONST("TO");
+	else if (MATCH("REVOKE #id"))
+		COMPLETE_WITH_CONST("FROM");
 
 	/*
 	 * Complete GRANT/REVOKE <sth> ON with a list of tables, views, and
@@ -3163,9 +2682,7 @@ psql_completion(const char *text, int start, int end)
 	 * here will only work if the privilege list contains exactly one
 	 * privilege.
 	 */
-	else if ((pg_strcasecmp(prev3_wd, "GRANT") == 0 ||
-			  pg_strcasecmp(prev3_wd, "REVOKE") == 0) &&
-			 pg_strcasecmp(prev_wd, "ON") == 0)
+	else if (MATCH("{GRANT|REVOKE} #kwd ON"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf,
 								   " UNION SELECT 'ALL FUNCTIONS IN SCHEMA'"
 								   " UNION SELECT 'ALL SEQUENCES IN SCHEMA'"
@@ -3183,10 +2700,7 @@ psql_completion(const char *text, int start, int end)
 								   " UNION SELECT 'TABLESPACE'"
 								   " UNION SELECT 'TYPE'");
 
-	else if ((pg_strcasecmp(prev4_wd, "GRANT") == 0 ||
-			  pg_strcasecmp(prev4_wd, "REVOKE") == 0) &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "ALL") == 0)
+	else if (MATCH("{GRANT|REVOKE} #kwd ON ALL"))
 	{
 		static const char *const list_privilege_all[] =
 		{"FUNCTIONS IN SCHEMA", "SEQUENCES IN SCHEMA", "TABLES IN SCHEMA",
@@ -3195,10 +2709,7 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(list_privilege_all);
 	}
 
-	else if ((pg_strcasecmp(prev4_wd, "GRANT") == 0 ||
-			  pg_strcasecmp(prev4_wd, "REVOKE") == 0) &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOREIGN") == 0)
+	else if (MATCH("{GRANT|REVOKE} #kwd ON FOREIGN"))
 	{
 		static const char *const list_privilege_foreign[] =
 		{"DATA WRAPPER", "SERVER", NULL};
@@ -3208,74 +2719,40 @@ psql_completion(const char *text, int start, int end)
 
 	/*
 	 * Complete "GRANT/REMOVE * ON DATABASE/DOMAIN/..." with a list of
-	 * appropriate objects.
+	 * appropriate objects later.
 	 *
-	 * Complete "GRANT/REVOKE * ON * " with "TO/FROM".
+	 * Complete only "GRANT/REVOKE * ON * " with "TO/FROM" here.
 	 */
-	else if ((pg_strcasecmp(prev4_wd, "GRANT") == 0 ||
-			  pg_strcasecmp(prev4_wd, "REVOKE") == 0) &&
-			 pg_strcasecmp(prev2_wd, "ON") == 0)
+	else if (MATCH("[GRANT|REVOKE] #kwd ON !DATABASE|DOMAIN|FUNCTION|LANGUAGE|SCHEMA|SEQUENCE|TABLE|TABLESPACE|TYPE"))
 	{
-		if (pg_strcasecmp(prev_wd, "DATABASE") == 0)
-			COMPLETE_WITH_QUERY(Query_for_list_of_databases, NULL);
-		else if (pg_strcasecmp(prev_wd, "DOMAIN") == 0)
-			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains, NULL);
-		else if (pg_strcasecmp(prev_wd, "FUNCTION") == 0)
-			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
-		else if (pg_strcasecmp(prev_wd, "LANGUAGE") == 0)
-			COMPLETE_WITH_QUERY(Query_for_list_of_languages, NULL);
-		else if (pg_strcasecmp(prev_wd, "SCHEMA") == 0)
-			COMPLETE_WITH_QUERY(Query_for_list_of_schemas, NULL);
-		else if (pg_strcasecmp(prev_wd, "SEQUENCE") == 0)
-			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences, NULL);
-		else if (pg_strcasecmp(prev_wd, "TABLE") == 0)
-			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf, NULL);
-		else if (pg_strcasecmp(prev_wd, "TABLESPACE") == 0)
-			COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces, NULL);
-		else if (pg_strcasecmp(prev_wd, "TYPE") == 0)
-			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
-		else if (pg_strcasecmp(prev4_wd, "GRANT") == 0)
+		if (pg_strcasecmp(CAPTURE(1), "GRANT") == 0)
 			COMPLETE_WITH_CONST("TO");
 		else
 			COMPLETE_WITH_CONST("FROM");
 	}
 
 	/* Complete "GRANT/REVOKE * ON ALL * IN SCHEMA *" with TO/FROM */
-	else if ((pg_strcasecmp(prev8_wd, "GRANT") == 0 ||
-			  pg_strcasecmp(prev8_wd, "REVOKE") == 0) &&
-			 pg_strcasecmp(prev6_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev5_wd, "ALL") == 0 &&
-			 pg_strcasecmp(prev3_wd, "IN") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SCHEMA") == 0)
-	{
-		if (pg_strcasecmp(prev8_wd, "GRANT") == 0)
+	else if (MATCH("[GRANT|REVOKE] #kwd ON ALL #kwd IN SCHEMA #id"))
+	{
+		if (pg_strcasecmp(CAPTURE(1), "GRANT") == 0)
 			COMPLETE_WITH_CONST("TO");
 		else
 			COMPLETE_WITH_CONST("FROM");
 	}
 
 	/* Complete "GRANT/REVOKE * ON FOREIGN DATA WRAPPER *" with TO/FROM */
-	else if ((pg_strcasecmp(prev7_wd, "GRANT") == 0 ||
-			  pg_strcasecmp(prev7_wd, "REVOKE") == 0) &&
-			 pg_strcasecmp(prev5_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev4_wd, "FOREIGN") == 0 &&
-			 pg_strcasecmp(prev3_wd, "DATA") == 0 &&
-			 pg_strcasecmp(prev2_wd, "WRAPPER") == 0)
-	{
-		if (pg_strcasecmp(prev7_wd, "GRANT") == 0)
+	else if (MATCH("[GRANT|REVOKE] #kwd ON FOREIGN DATA WRAPPER #id"))
+	{
+		if (pg_strcasecmp(CAPTURE(1), "GRANT") == 0)
 			COMPLETE_WITH_CONST("TO");
 		else
 			COMPLETE_WITH_CONST("FROM");
 	}
 
 	/* Complete "GRANT/REVOKE * ON FOREIGN SERVER *" with TO/FROM */
-	else if ((pg_strcasecmp(prev6_wd, "GRANT") == 0 ||
-			  pg_strcasecmp(prev6_wd, "REVOKE") == 0) &&
-			 pg_strcasecmp(prev4_wd, "ON") == 0 &&
-			 pg_strcasecmp(prev3_wd, "FOREIGN") == 0 &&
-			 pg_strcasecmp(prev2_wd, "SERVER") == 0)
+	else if (MATCH("[GRANT|REVOKE] #kwd ON FOREIGN SERVER #id"))
 	{
-		if (pg_strcasecmp(prev6_wd, "GRANT") == 0)
+		if (pg_strcasecmp(CAPTURE(1), "GRANT") == 0)
 			COMPLETE_WITH_CONST("TO");
 		else
 			COMPLETE_WITH_CONST("FROM");
@@ -3285,76 +2762,55 @@ psql_completion(const char *text, int start, int end)
 	 * Complete "GRANT/REVOKE ... TO/FROM" with username, PUBLIC,
 	 * CURRENT_USER, or SESSION_USER.
 	 */
-	else if (((pg_strcasecmp(prev9_wd, "GRANT") == 0 ||
-			   pg_strcasecmp(prev8_wd, "GRANT") == 0 ||
-			   pg_strcasecmp(prev7_wd, "GRANT") == 0 ||
-			   pg_strcasecmp(prev6_wd, "GRANT") == 0 ||
-			   pg_strcasecmp(prev5_wd, "GRANT") == 0) &&
-			  pg_strcasecmp(prev_wd, "TO") == 0) ||
-			 ((pg_strcasecmp(prev9_wd, "REVOKE") == 0 ||
-			   pg_strcasecmp(prev8_wd, "REVOKE") == 0 ||
-			   pg_strcasecmp(prev7_wd, "REVOKE") == 0 ||
-			   pg_strcasecmp(prev6_wd, "REVOKE") == 0 ||
-			   pg_strcasecmp(prev5_wd, "REVOKE") == 0) &&
-			  pg_strcasecmp(prev_wd, "FROM") == 0))
+	else if (MATCH("{GRANT|REVOKE}{ #nwb}+ {TO|FROM}"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles, NULL);
 
 	/* Complete "GRANT/REVOKE * ON * *" with TO/FROM */
-	else if (pg_strcasecmp(prev5_wd, "GRANT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0)
+	else if (MATCH("GRANT #kwd ON #kwd #id"))
 		COMPLETE_WITH_CONST("TO");
 
-	else if (pg_strcasecmp(prev5_wd, "REVOKE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0)
+	else if (MATCH("REVOKE #kwd ON #kwd #id"))
 		COMPLETE_WITH_CONST("FROM");
 
 	/*
 	 * Complete "GRANT/REVOKE * TO/FROM" with username, PUBLIC,
 	 * CURRENT_USER, or SESSION_USER.
 	 */
-	else if (pg_strcasecmp(prev3_wd, "GRANT") == 0 &&
-			 pg_strcasecmp(prev_wd, "TO") == 0)
-	{
+	else if (MATCH("GRANT #kwd TO"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles, NULL);
-	}
-	else if (pg_strcasecmp(prev3_wd, "REVOKE") == 0 &&
-			 pg_strcasecmp(prev_wd, "FROM") == 0)
-	{
+
+	else if (MATCH("REVOKE #kwd FROM"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles, NULL);
-	}
 
 /* GROUP BY */
-	else if (pg_strcasecmp(prev3_wd, "FROM") == 0 &&
-			 pg_strcasecmp(prev_wd, "GROUP") == 0)
+	else if (MATCH("FROM #id GROUP"))
 		COMPLETE_WITH_CONST("BY");
 
 /* IMPORT FOREIGN SCHEMA */
-	else if (pg_strcasecmp(prev_wd, "IMPORT") == 0)
+	else if (MATCH("IMPORT"))
 		COMPLETE_WITH_CONST("FOREIGN SCHEMA");
-	else if (pg_strcasecmp(prev2_wd, "IMPORT") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOREIGN") == 0)
+
+	else if (MATCH("IMPORT FOREIGN"))
 		COMPLETE_WITH_CONST("SCHEMA");
 
 /* INSERT */
 	/* Complete INSERT with "INTO" */
-	else if (pg_strcasecmp(prev_wd, "INSERT") == 0)
+	else if (MATCH("INSERT"))
 		COMPLETE_WITH_CONST("INTO");
+
 	/* Complete INSERT INTO with table names */
-	else if (pg_strcasecmp(prev2_wd, "INSERT") == 0 &&
-			 pg_strcasecmp(prev_wd, "INTO") == 0)
+	else if (MATCH("INSERT INTO"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables, NULL);
+
 	/* Complete "INSERT INTO <table> (" with attribute names */
-	else if (pg_strcasecmp(prev4_wd, "INSERT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "INTO") == 0 &&
-			 pg_strcasecmp(prev_wd, "(") == 0)
-		COMPLETE_WITH_ATTR(prev2_wd, "");
+	else if (MATCH("INSERT INTO [#id]("))
+		COMPLETE_WITH_ATTR(CAPTURE(1), "");
 
 	/*
 	 * Complete INSERT INTO <table> with "(" or "VALUES" or "SELECT" or
 	 * "TABLE" or "DEFAULT VALUES"
 	 */
-	else if (pg_strcasecmp(prev3_wd, "INSERT") == 0 &&
-			 pg_strcasecmp(prev2_wd, "INTO") == 0)
+	else if (MATCH("INSERT INTO #id"))
 	{
 		static const char *const list_INSERT[] =
 		{"(", "DEFAULT VALUES", "SELECT", "TABLE", "VALUES", NULL};
@@ -3366,9 +2822,7 @@ psql_completion(const char *text, int start, int end)
 	 * Complete INSERT INTO <table> (attribs) with "VALUES" or "SELECT" or
 	 * "TABLE"
 	 */
-	else if (pg_strcasecmp(prev4_wd, "INSERT") == 0 &&
-			 pg_strcasecmp(prev3_wd, "INTO") == 0 &&
-			 prev_wd[strlen(prev_wd) - 1] == ')')
+	else if (MATCH("INSERT INTO #id(..)"))
 	{
 		static const char *const list_INSERT[] =
 		{"SELECT", "TABLE", "VALUES", NULL};
@@ -3377,33 +2831,26 @@ psql_completion(const char *text, int start, int end)
 	}
 
 	/* Insert an open parenthesis after "VALUES" */
-	else if (pg_strcasecmp(prev_wd, "VALUES") == 0 &&
-			 pg_strcasecmp(prev2_wd, "DEFAULT") != 0)
+	else if (MATCH("!DEFAULT VALUES"))
 		COMPLETE_WITH_CONST("(");
 
 /* LOCK */
 	/* Complete LOCK [TABLE] with a list of tables */
-	else if (pg_strcasecmp(prev_wd, "LOCK") == 0)
+	else if (MATCH("LOCK"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
 								   " UNION SELECT 'TABLE'");
-	else if (pg_strcasecmp(prev_wd, "TABLE") == 0 &&
-			 pg_strcasecmp(prev2_wd, "LOCK") == 0)
+
+	else if (MATCH("LOCK TABLE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
 
 	/* For the following, handle the case of a single table only for now */
 
 	/* Complete LOCK [TABLE] <table> with "IN" */
-	else if ((pg_strcasecmp(prev2_wd, "LOCK") == 0 &&
-			  pg_strcasecmp(prev_wd, "TABLE") != 0) ||
-			 (pg_strcasecmp(prev2_wd, "TABLE") == 0 &&
-			  pg_strcasecmp(prev3_wd, "LOCK") == 0))
+	else if (MATCH("LOCK{ TABLE}? !TABLE"))
 		COMPLETE_WITH_CONST("IN");
 
 	/* Complete LOCK [TABLE] <table> IN with a lock mode */
-	else if (pg_strcasecmp(prev_wd, "IN") == 0 &&
-			 (pg_strcasecmp(prev3_wd, "LOCK") == 0 ||
-			  (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
-			   pg_strcasecmp(prev4_wd, "LOCK") == 0)))
+	else if (MATCH("LOCK{ TABLE}? #id IN"))
 	{
 		static const char *const lock_modes[] =
 		{"ACCESS SHARE MODE",
@@ -3416,30 +2863,26 @@ psql_completion(const char *text, int start, int end)
 	}
 
 /* NOTIFY */
-	else if (pg_strcasecmp(prev_wd, "NOTIFY") == 0)
+	else if (MATCH("NOTIFY"))
 		COMPLETE_WITH_QUERY("SELECT pg_catalog.quote_ident(channel) FROM pg_catalog.pg_listening_channels() AS channel WHERE substring(pg_catalog.quote_ident(channel),1,%d)='%s'", NULL);
 
 /* OPTIONS */
-	else if (pg_strcasecmp(prev_wd, "OPTIONS") == 0)
+	else if (MATCH("OPTIONS"))
 		COMPLETE_WITH_CONST("(");
 
 /* OWNER TO  - complete with available roles */
-	else if (pg_strcasecmp(prev2_wd, "OWNER") == 0 &&
-			 pg_strcasecmp(prev_wd, "TO") == 0)
+	else if (MATCH("OWNER TO"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
 
 /* ORDER BY */
-	else if (pg_strcasecmp(prev3_wd, "FROM") == 0 &&
-			 pg_strcasecmp(prev_wd, "ORDER") == 0)
+	else if (MATCH("FROM #id ORDER"))
 		COMPLETE_WITH_CONST("BY");
-	else if (pg_strcasecmp(prev4_wd, "FROM") == 0 &&
-			 pg_strcasecmp(prev2_wd, "ORDER") == 0 &&
-			 pg_strcasecmp(prev_wd, "BY") == 0)
-		COMPLETE_WITH_ATTR(prev3_wd, "");
+
+	else if (MATCH("FROM [#id] ORDER BY"))
+		COMPLETE_WITH_ATTR(CAPTURE(1), "");
 
 /* PREPARE xx AS */
-	else if (pg_strcasecmp(prev_wd, "AS") == 0 &&
-			 pg_strcasecmp(prev3_wd, "PREPARE") == 0)
+	else if (MATCH("PREPARE #id AS"))
 	{
 		static const char *const list_PREPARE[] =
 		{"SELECT", "UPDATE", "INSERT", "DELETE", NULL};
@@ -3453,116 +2896,68 @@ psql_completion(const char *text, int start, int end)
  */
 
 /* REASSIGN OWNED BY xxx TO yyy */
-	else if (pg_strcasecmp(prev_wd, "REASSIGN") == 0)
+	else if (MATCH("REASSIGN"))
 		COMPLETE_WITH_CONST("OWNED");
-	else if (pg_strcasecmp(prev_wd, "OWNED") == 0 &&
-			 pg_strcasecmp(prev2_wd, "REASSIGN") == 0)
+	else if (MATCH("REASSIGN OWNED"))
 		COMPLETE_WITH_CONST("BY");
-	else if (pg_strcasecmp(prev_wd, "BY") == 0 &&
-			 pg_strcasecmp(prev2_wd, "OWNED") == 0 &&
-			 pg_strcasecmp(prev3_wd, "REASSIGN") == 0)
+	else if (MATCH("REASSIGN OWNED BY"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
-	else if (pg_strcasecmp(prev2_wd, "BY") == 0 &&
-			 pg_strcasecmp(prev3_wd, "OWNED") == 0 &&
-			 pg_strcasecmp(prev4_wd, "REASSIGN") == 0)
+	else if (MATCH("REASSIGN OWNED BY #id"))
 		COMPLETE_WITH_CONST("TO");
-	else if (pg_strcasecmp(prev_wd, "TO") == 0 &&
-			 pg_strcasecmp(prev3_wd, "BY") == 0 &&
-			 pg_strcasecmp(prev4_wd, "OWNED") == 0 &&
-			 pg_strcasecmp(prev5_wd, "REASSIGN") == 0)
+	else if (MATCH("REASSIGN OWNED BY #id TO"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
 
 /* REFRESH MATERIALIZED VIEW */
-	else if (pg_strcasecmp(prev_wd, "REFRESH") == 0)
+	else if (MATCH("REFRESH"))
 		COMPLETE_WITH_CONST("MATERIALIZED VIEW");
-	else if (pg_strcasecmp(prev2_wd, "REFRESH") == 0 &&
-			 pg_strcasecmp(prev_wd, "MATERIALIZED") == 0)
+	else if (MATCH("REFRESH MATERIALIZED"))
 		COMPLETE_WITH_CONST("VIEW");
-	else if (pg_strcasecmp(prev3_wd, "REFRESH") == 0 &&
-			 pg_strcasecmp(prev2_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev_wd, "VIEW") == 0)
+	else if (MATCH("REFRESH MATERIALIZED VIEW"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews,
 								   " UNION SELECT 'CONCURRENTLY'");
-	else if (pg_strcasecmp(prev4_wd, "REFRESH") == 0 &&
-			 pg_strcasecmp(prev3_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev2_wd, "VIEW") == 0 &&
-			 pg_strcasecmp(prev_wd, "CONCURRENTLY") == 0)
+	else if (MATCH("REFRESH MATERIALIZED VIEW CONCURRENTLY"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
-	else if (pg_strcasecmp(prev4_wd, "REFRESH") == 0 &&
-			 pg_strcasecmp(prev3_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev2_wd, "VIEW") == 0)
+	else if (MATCH("REFRESH MATERIALIZED VIEW #id"))
 		COMPLETE_WITH_CONST("WITH");
-	else if (pg_strcasecmp(prev5_wd, "REFRESH") == 0 &&
-			 pg_strcasecmp(prev4_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev3_wd, "VIEW") == 0 &&
-			 pg_strcasecmp(prev2_wd, "CONCURRENTLY") == 0)
+	else if (MATCH("REFRESH MATERIALIZED VIEW CONCURRENTLY #id"))
 		COMPLETE_WITH_CONST("WITH DATA");
-	else if (pg_strcasecmp(prev5_wd, "REFRESH") == 0 &&
-			 pg_strcasecmp(prev4_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev3_wd, "VIEW") == 0 &&
-			 pg_strcasecmp(prev_wd, "WITH") == 0)
+	else if (MATCH("REFRESH MATERIALIZED VIEW #id WITH"))
 	{
 		static const char *const list_WITH_DATA[] =
 		{"NO DATA", "DATA", NULL};
 
 		COMPLETE_WITH_LIST(list_WITH_DATA);
 	}
-	else if (pg_strcasecmp(prev6_wd, "REFRESH") == 0 &&
-			 pg_strcasecmp(prev5_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev4_wd, "VIEW") == 0 &&
-			 pg_strcasecmp(prev3_wd, "CONCURRENTLY") == 0 &&
-			 pg_strcasecmp(prev_wd, "WITH") == 0)
+	else if (MATCH("REFRESH MATERIALIZED VIEW CONCURRENTLY #id WITH"))
 		COMPLETE_WITH_CONST("DATA");
-	else if (pg_strcasecmp(prev6_wd, "REFRESH") == 0 &&
-			 pg_strcasecmp(prev5_wd, "MATERIALIZED") == 0 &&
-			 pg_strcasecmp(prev4_wd, "VIEW") == 0 &&
-			 pg_strcasecmp(prev2_wd, "WITH") == 0 &&
-			 pg_strcasecmp(prev_wd, "NO") == 0)
+	else if (MATCH("REFRESH MATERIALIZED VIEW #id WITH NO"))
 		COMPLETE_WITH_CONST("DATA");
 
 /* REINDEX */
-	else if (pg_strcasecmp(prev_wd, "REINDEX") == 0)
+	else if (MATCH("REINDEX"))
 	{
 		static const char *const list_REINDEX[] =
 		{"TABLE", "INDEX", "SYSTEM", "SCHEMA", "DATABASE", NULL};
 
 		COMPLETE_WITH_LIST(list_REINDEX);
 	}
-	else if (pg_strcasecmp(prev2_wd, "REINDEX") == 0)
-	{
-		if (pg_strcasecmp(prev_wd, "TABLE") == 0)
-			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, NULL);
-		else if (pg_strcasecmp(prev_wd, "INDEX") == 0)
-			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
-		else if (pg_strcasecmp(prev_wd, "SCHEMA") == 0)
-			COMPLETE_WITH_QUERY(Query_for_list_of_schemas, NULL);
-		else if (pg_strcasecmp(prev_wd, "SYSTEM") == 0 ||
-				 pg_strcasecmp(prev_wd, "DATABASE") == 0)
-			COMPLETE_WITH_QUERY(Query_for_list_of_databases, NULL);
-	}
+	/* REINDEX {TABLE|INDEX|SCHEMA|DATABASE} are completed later */
+	else if (MATCH("REINDEX SYSTEM"))
+		COMPLETE_WITH_QUERY(Query_for_list_of_databases, NULL);
 
 /* SECURITY LABEL */
-	else if (pg_strcasecmp(prev_wd, "SECURITY") == 0)
+	else if (MATCH("SECURITY"))
 		COMPLETE_WITH_CONST("LABEL");
-	else if (pg_strcasecmp(prev2_wd, "SECURITY") == 0 &&
-			 pg_strcasecmp(prev_wd, "LABEL") == 0)
+	else if (MATCH("SECURITY LABEL"))
 	{
 		static const char *const list_SECURITY_LABEL_preposition[] =
 		{"ON", "FOR"};
 
 		COMPLETE_WITH_LIST(list_SECURITY_LABEL_preposition);
 	}
-	else if (pg_strcasecmp(prev4_wd, "SECURITY") == 0 &&
-			 pg_strcasecmp(prev3_wd, "LABEL") == 0 &&
-			 pg_strcasecmp(prev2_wd, "FOR") == 0)
+	else if (MATCH("SECURITY LABEL FOR #id"))
 		COMPLETE_WITH_CONST("ON");
-	else if ((pg_strcasecmp(prev3_wd, "SECURITY") == 0 &&
-			  pg_strcasecmp(prev2_wd, "LABEL") == 0 &&
-			  pg_strcasecmp(prev_wd, "ON") == 0) ||
-			 (pg_strcasecmp(prev5_wd, "SECURITY") == 0 &&
-			  pg_strcasecmp(prev4_wd, "LABEL") == 0 &&
-			  pg_strcasecmp(prev3_wd, "FOR") == 0 &&
-			  pg_strcasecmp(prev_wd, "ON") == 0))
+	else if (MATCH("SECURITY LABEL{ FOR #id}? ON"))
 	{
 		static const char *const list_SECURITY_LABEL[] =
 		{"LANGUAGE", "SCHEMA", "SEQUENCE", "TABLE", "TYPE", "VIEW",
@@ -3571,88 +2966,54 @@ psql_completion(const char *text, int start, int end)
 
 		COMPLETE_WITH_LIST(list_SECURITY_LABEL);
 	}
-	else if (pg_strcasecmp(prev5_wd, "SECURITY") == 0 &&
-			 pg_strcasecmp(prev4_wd, "LABEL") == 0 &&
-			 pg_strcasecmp(prev3_wd, "ON") == 0)
+	else if (MATCH("SECURITY LABEL ON #nwb #nwb"))
 		COMPLETE_WITH_CONST("IS");
 
 /* SELECT */
-	/* naah . . . */
+	/* naah . . . */ 
 
 /* SET, RESET, SHOW */
 	/* Complete with a variable name */
-	else if ((pg_strcasecmp(prev_wd, "SET") == 0 &&
-			  pg_strcasecmp(prev3_wd, "UPDATE") != 0) ||
-			 pg_strcasecmp(prev_wd, "RESET") == 0)
+	else if (MATCH("^{RE}?SET"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_set_vars, NULL);
-	else if (pg_strcasecmp(prev_wd, "SHOW") == 0)
+	else if (MATCH("SHOW"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_show_vars, NULL);
+
 	/* Complete "SET TRANSACTION" */
-	else if ((pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			  pg_strcasecmp(prev_wd, "TRANSACTION") == 0)
-			 || (pg_strcasecmp(prev2_wd, "START") == 0
-				 && pg_strcasecmp(prev_wd, "TRANSACTION") == 0)
-			 || (pg_strcasecmp(prev2_wd, "BEGIN") == 0
-				 && pg_strcasecmp(prev_wd, "WORK") == 0)
-			 || (pg_strcasecmp(prev2_wd, "BEGIN") == 0
-				 && pg_strcasecmp(prev_wd, "TRANSACTION") == 0)
-			 || (pg_strcasecmp(prev4_wd, "SESSION") == 0
-				 && pg_strcasecmp(prev3_wd, "CHARACTERISTICS") == 0
-				 && pg_strcasecmp(prev2_wd, "AS") == 0
-				 && pg_strcasecmp(prev_wd, "TRANSACTION") == 0))
+	else if (MATCH("{{{SET|START} TRANSACTION}|"
+				 "{BEGIN {TRANSACTION|WORK}}|"
+				 "{SESSION CHARACTERISTICS AS TRANSACTION}}"))
 	{
 		static const char *const my_list[] =
 		{"ISOLATION LEVEL", "READ", NULL};
 
 		COMPLETE_WITH_LIST(my_list);
 	}
-	else if ((pg_strcasecmp(prev3_wd, "SET") == 0
-			  || pg_strcasecmp(prev3_wd, "BEGIN") == 0
-			  || pg_strcasecmp(prev3_wd, "START") == 0
-			  || (pg_strcasecmp(prev4_wd, "CHARACTERISTICS") == 0
-				  && pg_strcasecmp(prev3_wd, "AS") == 0))
-			 && (pg_strcasecmp(prev2_wd, "TRANSACTION") == 0
-				 || pg_strcasecmp(prev2_wd, "WORK") == 0)
-			 && pg_strcasecmp(prev_wd, "ISOLATION") == 0)
+	else if (MATCH("{{{SET|START} TRANSACTION}|"
+				 "{BEGIN {TRANSACTION|WORK}}|"
+				 "{SESSION CHARACTERISTICS AS TRANSACTION}}"
+				" ISOLATION"))
 		COMPLETE_WITH_CONST("LEVEL");
-	else if ((pg_strcasecmp(prev4_wd, "SET") == 0
-			  || pg_strcasecmp(prev4_wd, "BEGIN") == 0
-			  || pg_strcasecmp(prev4_wd, "START") == 0
-			  || pg_strcasecmp(prev4_wd, "AS") == 0)
-			 && (pg_strcasecmp(prev3_wd, "TRANSACTION") == 0
-				 || pg_strcasecmp(prev3_wd, "WORK") == 0)
-			 && pg_strcasecmp(prev2_wd, "ISOLATION") == 0
-			 && pg_strcasecmp(prev_wd, "LEVEL") == 0)
+	else if (MATCH("{{{SET|START} TRANSACTION}|"
+				 "{BEGIN {TRANSACTION|WORK}}|"
+				 "{SESSION CHARACTERISTICS AS TRANSACTION}}"
+				" ISOLATION LEVEL"))
 	{
 		static const char *const my_list[] =
 		{"READ", "REPEATABLE", "SERIALIZABLE", NULL};
 
 		COMPLETE_WITH_LIST(my_list);
 	}
-	else if ((pg_strcasecmp(prev4_wd, "TRANSACTION") == 0 ||
-			  pg_strcasecmp(prev4_wd, "WORK") == 0) &&
-			 pg_strcasecmp(prev3_wd, "ISOLATION") == 0 &&
-			 pg_strcasecmp(prev2_wd, "LEVEL") == 0 &&
-			 pg_strcasecmp(prev_wd, "READ") == 0)
+	else if (MATCH("{TRANSACTION|WORK} ISOLATION LEVEL READ"))
 	{
 		static const char *const my_list[] =
 		{"UNCOMMITTED", "COMMITTED", NULL};
 
 		COMPLETE_WITH_LIST(my_list);
 	}
-	else if ((pg_strcasecmp(prev4_wd, "TRANSACTION") == 0 ||
-			  pg_strcasecmp(prev4_wd, "WORK") == 0) &&
-			 pg_strcasecmp(prev3_wd, "ISOLATION") == 0 &&
-			 pg_strcasecmp(prev2_wd, "LEVEL") == 0 &&
-			 pg_strcasecmp(prev_wd, "REPEATABLE") == 0)
+	else if (MATCH("{TRANSACTION|WORK} ISOLATION LEVEL REPEATABLE"))
 		COMPLETE_WITH_CONST("READ");
-	else if ((pg_strcasecmp(prev3_wd, "SET") == 0 ||
-			  pg_strcasecmp(prev3_wd, "BEGIN") == 0 ||
-			  pg_strcasecmp(prev3_wd, "START") == 0 ||
-			  pg_strcasecmp(prev3_wd, "AS") == 0) &&
-			 (pg_strcasecmp(prev2_wd, "TRANSACTION") == 0 ||
-			  pg_strcasecmp(prev2_wd, "WORK") == 0) &&
-			 pg_strcasecmp(prev_wd, "READ") == 0)
+	else if (MATCH("{SET|BEGIN|START|AS} {TRANSACTION|WORK} READ"))
 	{
 		static const char *const my_list[] =
 		{"ONLY", "WRITE", NULL};
@@ -3660,14 +3021,12 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(my_list);
 	}
 	/* SET CONSTRAINTS */
-	else if (pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev_wd, "CONSTRAINTS") == 0)
+	else if (MATCH("SET CONSTRAINTS"))
 	{
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_constraints_with_schema, "UNION SELECT 'ALL'");
 	}
 	/* Complete SET CONSTRAINTS <foo> with DEFERRED|IMMEDIATE */
-	else if (pg_strcasecmp(prev3_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev2_wd, "CONSTRAINTS") == 0)
+	else if (MATCH("SET CONSTRAINTS #id"))
 	{
 		static const char *const constraint_list[] =
 		{"DEFERRED", "IMMEDIATE", NULL};
@@ -3675,12 +3034,10 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(constraint_list);
 	}
 	/* Complete SET ROLE */
-	else if (pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev_wd, "ROLE") == 0)
+	else if (MATCH("SET ROLE"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
 	/* Complete SET SESSION with AUTHORIZATION or CHARACTERISTICS... */
-	else if (pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev_wd, "SESSION") == 0)
+	else if (MATCH("SET SESSION"))
 	{
 		static const char *const my_list[] =
 		{"AUTHORIZATION", "CHARACTERISTICS AS TRANSACTION", NULL};
@@ -3688,30 +3045,23 @@ psql_completion(const char *text, int start, int end)
 		COMPLETE_WITH_LIST(my_list);
 	}
 	/* Complete SET SESSION AUTHORIZATION with username */
-	else if (pg_strcasecmp(prev3_wd, "SET") == 0
-			 && pg_strcasecmp(prev2_wd, "SESSION") == 0
-			 && pg_strcasecmp(prev_wd, "AUTHORIZATION") == 0)
+	else if (MATCH("SET SESSION AUTHORIZATION"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles " UNION SELECT 'DEFAULT'",
 							NULL);
 	/* Complete RESET SESSION with AUTHORIZATION */
-	else if (pg_strcasecmp(prev2_wd, "RESET") == 0 &&
-			 pg_strcasecmp(prev_wd, "SESSION") == 0)
+	else if (MATCH("RESET SESSION"))
 		COMPLETE_WITH_CONST("AUTHORIZATION");
+
 	/* Complete SET <var> with "TO" */
-	else if (pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev4_wd, "UPDATE") != 0 &&
-			 pg_strcasecmp(prev_wd, "TABLESPACE") != 0 &&
-			 pg_strcasecmp(prev_wd, "SCHEMA") != 0 &&
-			 prev_wd[strlen(prev_wd) - 1] != ')' &&
-			 prev_wd[strlen(prev_wd) - 1] != '=' &&
-			 pg_strcasecmp(prev4_wd, "DOMAIN") != 0)
+	else if (MATCH("^{!UPDATE }*SET !TABLESPACE|SCHEMA|="))
 		COMPLETE_WITH_CONST("TO");
+
 	/* Suggest possible variable values */
-	else if (pg_strcasecmp(prev3_wd, "SET") == 0 &&
-			 (pg_strcasecmp(prev_wd, "TO") == 0 || strcmp(prev_wd, "=") == 0))
+	else if (MATCH("SET [#id] {TO|=}"))
 	{
+		CAPTURE0(1);
 		/* special cased code for individual GUCs */
-		if (pg_strcasecmp(prev2_wd, "DateStyle") == 0)
+		if (pg_strcasecmp(CAPBUF(1), "DateStyle") == 0)
 		{
 			static const char *const my_list[] =
 			{"ISO", "SQL", "Postgres", "German",
@@ -3721,7 +3071,7 @@ psql_completion(const char *text, int start, int end)
 
 			COMPLETE_WITH_LIST(my_list);
 		}
-		else if (pg_strcasecmp(prev2_wd, "search_path") == 0)
+		else if (pg_strcasecmp(CAPBUF(1), "search_path") == 0)
 		{
 			COMPLETE_WITH_QUERY(Query_for_list_of_schemas
 								" AND nspname not like 'pg\\_toast%%' "
@@ -3733,13 +3083,13 @@ psql_completion(const char *text, int start, int end)
 		{
 			/* generic, type based, GUC support */
 
-			char	   *guctype = get_guctype(prev2_wd);
+			char	   *guctype = get_guctype(CAPBUF(1));
 
 			if (guctype && strcmp(guctype, "enum") == 0)
 			{
 				char		querybuf[1024];
 
-				snprintf(querybuf, 1024, Query_for_enum, prev2_wd);
+				snprintf(querybuf, 1024, Query_for_enum, CAPBUF(1));
 				COMPLETE_WITH_QUERY(querybuf, NULL);
 			}
 			else if (guctype && strcmp(guctype, "bool") == 0)
@@ -3763,35 +3113,34 @@ psql_completion(const char *text, int start, int end)
 	}
 
 /* START TRANSACTION */
-	else if (pg_strcasecmp(prev_wd, "START") == 0)
+	else if (MATCH("START"))
 		COMPLETE_WITH_CONST("TRANSACTION");
 
 /* TABLE, but not TABLE embedded in other commands */
-	else if (pg_strcasecmp(prev_wd, "TABLE") == 0 &&
-			 prev2_wd[0] == '\0')
+	else if (MATCH("^TABLE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_relations, NULL);
 
 /* TABLESAMPLE */
-	else if (pg_strcasecmp(prev_wd, "TABLESAMPLE") == 0)
+	else if (MATCH("TABLESAMPLE"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_tablesample_methods, NULL);
 
-	else if (pg_strcasecmp(prev2_wd, "TABLESAMPLE") == 0)
+	else if (MATCH("TABLESAMPLE #id"))
 		COMPLETE_WITH_CONST("(");
 
 /* TRUNCATE */
-	else if (pg_strcasecmp(prev_wd, "TRUNCATE") == 0)
+	else if (MATCH("TRUNCATE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
 
 /* UNLISTEN */
-	else if (pg_strcasecmp(prev_wd, "UNLISTEN") == 0)
+	else if (MATCH("UNLISTEN"))
 		COMPLETE_WITH_QUERY("SELECT pg_catalog.quote_ident(channel) FROM pg_catalog.pg_listening_channels() AS channel WHERE substring(pg_catalog.quote_ident(channel),1,%d)='%s' UNION SELECT '*'", NULL);
 
 /* UPDATE */
 	/* If prev. word is UPDATE suggest a list of tables */
-	else if (pg_strcasecmp(prev_wd, "UPDATE") == 0)
+	else if (MATCH("UPDATE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables, NULL);
 	/* Complete UPDATE <table> with "SET" */
-	else if (pg_strcasecmp(prev2_wd, "UPDATE") == 0)
+	else if (MATCH("UPDATE #id"))
 		COMPLETE_WITH_CONST("SET");
 
 	/*
@@ -3799,83 +3148,55 @@ psql_completion(const char *text, int start, int end)
 	 * word) the word before it was (hopefully) a table name and we'll now
 	 * make a list of attributes.
 	 */
-	else if (pg_strcasecmp(prev_wd, "SET") == 0)
-		COMPLETE_WITH_ATTR(prev2_wd, "");
+	else if (MATCH("[#id] SET"))
+		COMPLETE_WITH_ATTR(CAPTURE(1), "");
 
 /* UPDATE xx SET yy = */
-	else if (pg_strcasecmp(prev2_wd, "SET") == 0 &&
-			 pg_strcasecmp(prev4_wd, "UPDATE") == 0)
+	else if (MATCH("UPDATE #id SET #id"))
 		COMPLETE_WITH_CONST("=");
 
 /* USER MAPPING */
-	else if ((pg_strcasecmp(prev3_wd, "ALTER") == 0 ||
-			  pg_strcasecmp(prev3_wd, "CREATE") == 0 ||
-			  pg_strcasecmp(prev3_wd, "DROP") == 0) &&
-			 pg_strcasecmp(prev2_wd, "USER") == 0 &&
-			 pg_strcasecmp(prev_wd, "MAPPING") == 0)
+	else if (MATCH("{ALTER|DROP|CREATE} USER MAPPING"))
 		COMPLETE_WITH_CONST("FOR");
-	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
-			 pg_strcasecmp(prev3_wd, "USER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "MAPPING") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOR") == 0)
+
+	else if (MATCH("CREATE USER MAPPING FOR"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles
 							" UNION SELECT 'CURRENT_USER'"
 							" UNION SELECT 'PUBLIC'"
 							" UNION SELECT 'USER'", NULL);
-	else if ((pg_strcasecmp(prev4_wd, "ALTER") == 0 ||
-			  pg_strcasecmp(prev4_wd, "DROP") == 0) &&
-			 pg_strcasecmp(prev3_wd, "USER") == 0 &&
-			 pg_strcasecmp(prev2_wd, "MAPPING") == 0 &&
-			 pg_strcasecmp(prev_wd, "FOR") == 0)
+	else if (MATCH("{ALTER|DROP} USER MAPPING FOR"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings, NULL);
-	else if ((pg_strcasecmp(prev5_wd, "CREATE") == 0 ||
-			  pg_strcasecmp(prev5_wd, "ALTER") == 0 ||
-			  pg_strcasecmp(prev5_wd, "DROP") == 0) &&
-			 pg_strcasecmp(prev4_wd, "USER") == 0 &&
-			 pg_strcasecmp(prev3_wd, "MAPPING") == 0 &&
-			 pg_strcasecmp(prev2_wd, "FOR") == 0)
+
+	else if (MATCH("{CREATE|ALTER|DROP} USER MAPPING FOR #id"))
 		COMPLETE_WITH_CONST("SERVER");
 
 /*
  * VACUUM [ FULL | FREEZE ] [ VERBOSE ] [ table ]
  * VACUUM [ FULL | FREEZE ] [ VERBOSE ] ANALYZE [ table [ (column [, ...] ) ] ]
  */
-	else if (pg_strcasecmp(prev_wd, "VACUUM") == 0)
+	else if (MATCH("VACUUM"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm,
 								   " UNION SELECT 'FULL'"
 								   " UNION SELECT 'FREEZE'"
 								   " UNION SELECT 'ANALYZE'"
 								   " UNION SELECT 'VERBOSE'");
-	else if (pg_strcasecmp(prev2_wd, "VACUUM") == 0 &&
-			 (pg_strcasecmp(prev_wd, "FULL") == 0 ||
-			  pg_strcasecmp(prev_wd, "FREEZE") == 0))
+	else if (MATCH("VACUUM {FULL|FREEZE}"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm,
 								   " UNION SELECT 'ANALYZE'"
 								   " UNION SELECT 'VERBOSE'");
-	else if (pg_strcasecmp(prev3_wd, "VACUUM") == 0 &&
-			 pg_strcasecmp(prev_wd, "ANALYZE") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "FULL") == 0 ||
-			  pg_strcasecmp(prev2_wd, "FREEZE") == 0))
+	else if (MATCH("VACUUM {FULL|FREEZE} ANALYZE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm,
 								   " UNION SELECT 'VERBOSE'");
-	else if (pg_strcasecmp(prev3_wd, "VACUUM") == 0 &&
-			 pg_strcasecmp(prev_wd, "VERBOSE") == 0 &&
-			 (pg_strcasecmp(prev2_wd, "FULL") == 0 ||
-			  pg_strcasecmp(prev2_wd, "FREEZE") == 0))
+	else if (MATCH("VACUUM {FULL|FREEZE} VERBOSE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm,
 								   " UNION SELECT 'ANALYZE'");
-	else if (pg_strcasecmp(prev2_wd, "VACUUM") == 0 &&
-			 pg_strcasecmp(prev_wd, "VERBOSE") == 0)
+	else if (MATCH("VACUUM VERBOSE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm,
 								   " UNION SELECT 'ANALYZE'");
-	else if (pg_strcasecmp(prev2_wd, "VACUUM") == 0 &&
-			 pg_strcasecmp(prev_wd, "ANALYZE") == 0)
+	else if (MATCH("VACUUM ANALYZE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm,
 								   " UNION SELECT 'VERBOSE'");
-	else if ((pg_strcasecmp(prev_wd, "ANALYZE") == 0 &&
-			  pg_strcasecmp(prev2_wd, "VERBOSE") == 0) ||
-			 (pg_strcasecmp(prev_wd, "VERBOSE") == 0 &&
-			  pg_strcasecmp(prev2_wd, "ANALYZE") == 0))
+	else if (MATCH("{{VERBOSE ANALYZE}|{ANALYZE VERBOSE}}"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, NULL);
 
 /* WITH [RECURSIVE] */
@@ -3884,120 +3205,115 @@ psql_completion(const char *text, int start, int end)
 	 * Only match when WITH is the first word, as WITH may appear in many
 	 * other contexts.
 	 */
-	else if (pg_strcasecmp(prev_wd, "WITH") == 0 &&
-			 prev2_wd[0] == '\0')
+	else if (MATCH("^WITH"))
 		COMPLETE_WITH_CONST("RECURSIVE");
 
 /* ANALYZE */
 	/* If the previous word is ANALYZE, produce list of tables */
-	else if (pg_strcasecmp(prev_wd, "ANALYZE") == 0)
+	else if (MATCH("ANALYZE"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tmf, NULL);
 
 /* WHERE */
 	/* Simple case of the word before the where being the table name */
-	else if (pg_strcasecmp(prev_wd, "WHERE") == 0)
-		COMPLETE_WITH_ATTR(prev2_wd, "");
+	else if (MATCH("[#id] WHERE"))
+		COMPLETE_WITH_ATTR(CAPTURE(1), "");
 
 /* ... FROM ... */
 /* TODO: also include SRF ? */
-	else if (pg_strcasecmp(prev_wd, "FROM") == 0 &&
-			 pg_strcasecmp(prev3_wd, "COPY") != 0 &&
-			 pg_strcasecmp(prev3_wd, "\\copy") != 0)
+	else if (MATCH("^{!\\?COPY }+FROM"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf, NULL);
 
 /* ... JOIN ... */
-	else if (pg_strcasecmp(prev_wd, "JOIN") == 0)
+	else if (MATCH("JOIN"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf, NULL);
 
 /* Backslash commands */
 /* TODO:  \dc \dd \dl */
-	else if (strcmp(prev_wd, "\\?") == 0)
+	else if (MATCH("\\#?_")) /* _ is necessary due to patcomp()'s design */
 	{
 		static const char *const my_list[] =
 		{"commands", "options", "variables", NULL};
 
 		COMPLETE_WITH_LIST_CS(my_list);
 	}
-	else if (strcmp(prev_wd, "\\connect") == 0 || strcmp(prev_wd, "\\c") == 0)
+	else if (CMATCH("\\c{onnect}?"))
 	{
 		if (!recognized_connection_string(text))
 			COMPLETE_WITH_QUERY(Query_for_list_of_databases, NULL);
 	}
-	else if (strcmp(prev2_wd, "\\connect") == 0 || strcmp(prev2_wd, "\\c") == 0)
+	else if (CMATCH("\\c{onnect}? [#id]"))
 	{
-		if (!recognized_connection_string(prev_wd))
+		if (!recognized_connection_string(CAPTURE(1)))
 			COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
 	}
-	else if (strncmp(prev_wd, "\\da", strlen("\\da")) == 0)
+	else if (CMATCH("\\da#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_aggregates, NULL);
-	else if (strncmp(prev_wd, "\\db", strlen("\\db")) == 0)
+	else if (CMATCH("\\db#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces, NULL);
-	else if (strncmp(prev_wd, "\\dD", strlen("\\dD")) == 0)
+	else if (CMATCH("\\dD#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains, NULL);
-	else if (strncmp(prev_wd, "\\des", strlen("\\des")) == 0)
+	else if (CMATCH("\\des#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_servers, NULL);
-	else if (strncmp(prev_wd, "\\deu", strlen("\\deu")) == 0)
+	else if (CMATCH("\\deu#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings, NULL);
-	else if (strncmp(prev_wd, "\\dew", strlen("\\dew")) == 0)
+	else if (CMATCH("\\dew#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_fdws, NULL);
 
-	else if (strncmp(prev_wd, "\\df", strlen("\\df")) == 0)
+	else if (CMATCH("\\df#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
-	else if (strncmp(prev_wd, "\\dFd", strlen("\\dFd")) == 0)
+	else if (CMATCH("\\dFd#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_ts_dictionaries, NULL);
-	else if (strncmp(prev_wd, "\\dFp", strlen("\\dFp")) == 0)
+	else if (CMATCH("\\dFp#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_ts_parsers, NULL);
-	else if (strncmp(prev_wd, "\\dFt", strlen("\\dFt")) == 0)
+	else if (CMATCH("\\dFt#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_ts_templates, NULL);
 	/* must be at end of \dF */
-	else if (strncmp(prev_wd, "\\dF", strlen("\\dF")) == 0)
+	else if (CMATCH("\\dF#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_ts_configurations, NULL);
 
-	else if (strncmp(prev_wd, "\\di", strlen("\\di")) == 0)
+	else if (CMATCH("\\di#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
-	else if (strncmp(prev_wd, "\\dL", strlen("\\dL")) == 0)
+	else if (CMATCH("\\dL#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_languages, NULL);
-	else if (strncmp(prev_wd, "\\dn", strlen("\\dn")) == 0)
+	else if (CMATCH("\\dn#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_schemas, NULL);
-	else if (strncmp(prev_wd, "\\dp", strlen("\\dp")) == 0
-			 || strncmp(prev_wd, "\\z", strlen("\\z")) == 0)
+	else if (CMATCH("\\{dp|z}#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf, NULL);
-	else if (strncmp(prev_wd, "\\ds", strlen("\\ds")) == 0)
+	else if (CMATCH("\\ds#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences, NULL);
-	else if (strncmp(prev_wd, "\\dt", strlen("\\dt")) == 0)
+	else if (CMATCH("\\dt#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
-	else if (strncmp(prev_wd, "\\dT", strlen("\\dT")) == 0)
+	else if (CMATCH("\\dT#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
-	else if (strncmp(prev_wd, "\\du", strlen("\\du")) == 0
-			 || (strncmp(prev_wd, "\\dg", strlen("\\dg")) == 0))
+	else if (CMATCH("\\d{u|g}#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
-	else if (strncmp(prev_wd, "\\dv", strlen("\\dv")) == 0)
+	else if (CMATCH("\\dv#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
-	else if (strncmp(prev_wd, "\\dx", strlen("\\dx")) == 0)
+	else if (CMATCH("\\dx#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_extensions, NULL);
-	else if (strncmp(prev_wd, "\\dm", strlen("\\dm")) == 0)
+	else if (CMATCH("\\dm#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
-	else if (strncmp(prev_wd, "\\dE", strlen("\\dE")) == 0)
+	else if (CMATCH("\\dE#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables, NULL);
-	else if (strncmp(prev_wd, "\\dy", strlen("\\dy")) == 0)
+	else if (CMATCH("\\dy#nsp"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers, NULL);
 
 	/* must be at end of \d list */
-	else if (strncmp(prev_wd, "\\d", strlen("\\d")) == 0)
+	else if (CMATCH("\\d#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_relations, NULL);
 
-	else if (strcmp(prev_wd, "\\ef") == 0)
+	else if (CMATCH("\\ef#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
-	else if (strcmp(prev_wd, "\\ev") == 0)
+	else if (CMATCH("\\ev#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
 
-	else if (strcmp(prev_wd, "\\encoding") == 0)
+	else if (CMATCH("\\encoding"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_encodings, NULL);
-	else if (strcmp(prev_wd, "\\h") == 0 || strcmp(prev_wd, "\\help") == 0)
+	else if (CMATCH("\\h{elp}?"))
 		COMPLETE_WITH_LIST(sql_commands);
-	else if (strcmp(prev_wd, "\\password") == 0)
+	else if (CMATCH("\\password"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_roles, NULL);
-	else if (strcmp(prev_wd, "\\pset") == 0)
+	else if (CMATCH("\\pset"))
 	{
 		static const char *const my_list[] =
 		{"border", "columns", "expanded", "fieldsep", "fieldsep_zero",
@@ -4008,9 +3324,10 @@ psql_completion(const char *text, int start, int end)
 
 		COMPLETE_WITH_LIST_CS(my_list);
 	}
-	else if (strcmp(prev2_wd, "\\pset") == 0)
+	else if (CMATCH("\\pset [#kwd]"))
 	{
-		if (strcmp(prev_wd, "format") == 0)
+		CAPTURE0(1);
+		if (strcmp(CAPBUF(1), "format") == 0)
 		{
 			static const char *const my_list[] =
 			{"unaligned", "aligned", "wrapped", "html", "asciidoc",
@@ -4018,16 +3335,16 @@ psql_completion(const char *text, int start, int end)
 
 			COMPLETE_WITH_LIST_CS(my_list);
 		}
-		else if (strcmp(prev_wd, "linestyle") == 0)
+		else if (strcmp(CAPBUF(1), "linestyle") == 0)
 		{
 			static const char *const my_list[] =
 			{"ascii", "old-ascii", "unicode", NULL};
 
 			COMPLETE_WITH_LIST_CS(my_list);
 		}
-		else if (strcmp(prev_wd, "unicode_border_linestyle") == 0 ||
-				 strcmp(prev_wd, "unicode_column_linestyle") == 0 ||
-				 strcmp(prev_wd, "unicode_header_linestyle") == 0)
+		else if (strcmp(CAPBUF(1), "unicode_border_linestyle") == 0 ||
+				 strcmp(CAPBUF(1), "unicode_column_linestyle") == 0 ||
+				 strcmp(CAPBUF(1), "unicode_header_linestyle") == 0)
 		{
 			static const char *const my_list[] =
 			{"single", "double", NULL};
@@ -4036,72 +3353,74 @@ psql_completion(const char *text, int start, int end)
 
 		}
 	}
-	else if (strcmp(prev_wd, "\\unset") == 0)
+	else if (CMATCH("\\unset"))
 	{
 		matches = complete_from_variables(text, "", "", true);
 	}
-	else if (strcmp(prev_wd, "\\set") == 0)
+	else if (CMATCH("\\set"))
 	{
 		matches = complete_from_variables(text, "", "", false);
 	}
-	else if (strcmp(prev2_wd, "\\set") == 0)
+	else if (CMATCH("\\set [#kwd]"))
 	{
 		static const char *const boolean_value_list[] =
 		{"on", "off", NULL};
 
-		if (strcmp(prev_wd, "AUTOCOMMIT") == 0)
+		CAPTURE0(1);
+
+		if (strcmp(CAPBUF(1), "AUTOCOMMIT") == 0)
 			COMPLETE_WITH_LIST_CS(boolean_value_list);
-		else if (strcmp(prev_wd, "COMP_KEYWORD_CASE") == 0)
+		else if (strcmp(CAPBUF(1), "COMP_KEYWORD_CASE") == 0)
 		{
 			static const char *const my_list[] =
 			{"lower", "upper", "preserve-lower", "preserve-upper", NULL};
 
 			COMPLETE_WITH_LIST_CS(my_list);
 		}
-		else if (strcmp(prev_wd, "ECHO") == 0)
+		else if (strcmp(CAPBUF(1), "ECHO") == 0)
 		{
 			static const char *const my_list[] =
 			{"errors", "queries", "all", "none", NULL};
 
 			COMPLETE_WITH_LIST_CS(my_list);
 		}
-		else if (strcmp(prev_wd, "ECHO_HIDDEN") == 0)
+		else if (strcmp(CAPBUF(1), "ECHO_HIDDEN") == 0)
 		{
 			static const char *const my_list[] =
 			{"noexec", "off", "on", NULL};
 
 			COMPLETE_WITH_LIST_CS(my_list);
 		}
-		else if (strcmp(prev_wd, "HISTCONTROL") == 0)
+		else if (strcmp(CAPBUF(1), "HISTCONTROL") == 0)
 		{
 			static const char *const my_list[] =
 			{"ignorespace", "ignoredups", "ignoreboth", "none", NULL};
 
 			COMPLETE_WITH_LIST_CS(my_list);
 		}
-		else if (strcmp(prev_wd, "ON_ERROR_ROLLBACK") == 0)
+		else if (strcmp(CAPBUF(1), "ON_ERROR_ROLLBACK") == 0)
 		{
 			static const char *const my_list[] =
 			{"on", "off", "interactive", NULL};
 
 			COMPLETE_WITH_LIST_CS(my_list);
 		}
-		else if (strcmp(prev_wd, "ON_ERROR_STOP") == 0)
+		else if (strcmp(CAPBUF(1), "ON_ERROR_STOP") == 0)
 			COMPLETE_WITH_LIST_CS(boolean_value_list);
-		else if (strcmp(prev_wd, "QUIET") == 0)
+		else if (strcmp(CAPBUF(1), "QUIET") == 0)
 			COMPLETE_WITH_LIST_CS(boolean_value_list);
-		else if (strcmp(prev_wd, "SHOW_CONTEXT") == 0)
+		else if (strcmp(CAPBUF(1), "SHOW_CONTEXT") == 0)
 		{
 			static const char *const my_list[] =
 			{"never", "errors", "always", NULL};
 
 			COMPLETE_WITH_LIST_CS(my_list);
 		}
-		else if (strcmp(prev_wd, "SINGLELINE") == 0)
+		else if (strcmp(CAPBUF(1), "SINGLELINE") == 0)
 			COMPLETE_WITH_LIST_CS(boolean_value_list);
-		else if (strcmp(prev_wd, "SINGLESTEP") == 0)
+		else if (strcmp(CAPBUF(1), "SINGLESTEP") == 0)
 			COMPLETE_WITH_LIST_CS(boolean_value_list);
-		else if (strcmp(prev_wd, "VERBOSITY") == 0)
+		else if (strcmp(CAPBUF(1), "VERBOSITY") == 0)
 		{
 			static const char *const my_list[] =
 			{"default", "verbose", "terse", NULL};
@@ -4109,20 +3428,11 @@ psql_completion(const char *text, int start, int end)
 			COMPLETE_WITH_LIST_CS(my_list);
 		}
 	}
-	else if (strcmp(prev_wd, "\\sf") == 0 || strcmp(prev_wd, "\\sf+") == 0)
+	else if (CMATCH("\\sf#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
-	else if (strcmp(prev_wd, "\\sv") == 0 || strcmp(prev_wd, "\\sv+") == 0)
+	else if (CMATCH("\\sv#nsp"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
-	else if (strcmp(prev_wd, "\\cd") == 0 ||
-			 strcmp(prev_wd, "\\e") == 0 || strcmp(prev_wd, "\\edit") == 0 ||
-			 strcmp(prev_wd, "\\g") == 0 ||
-		  strcmp(prev_wd, "\\i") == 0 || strcmp(prev_wd, "\\include") == 0 ||
-			 strcmp(prev_wd, "\\ir") == 0 || strcmp(prev_wd, "\\include_relative") == 0 ||
-			 strcmp(prev_wd, "\\o") == 0 || strcmp(prev_wd, "\\out") == 0 ||
-			 strcmp(prev_wd, "\\s") == 0 ||
-			 strcmp(prev_wd, "\\w") == 0 || strcmp(prev_wd, "\\write") == 0 ||
-			 strcmp(prev_wd, "\\lo_import") == 0
-		)
+	else if (CMATCH("\\{cd|e|edit|g|i|include|ir|include_relative|o|out|s|w|write|lo_import}"))
 	{
 		completion_charp = "\\";
 		matches = completion_matches(text, complete_from_files);
@@ -4133,13 +3443,14 @@ psql_completion(const char *text, int start, int end)
 	 * check if that was the previous word. If so, execute the query to get a
 	 * list of them.
 	 */
-	else
+	else if(MATCH("[#kwd]"))
 	{
 		int			i;
 
+		CAPTURE0(1);
 		for (i = 0; words_after_create[i].name; i++)
 		{
-			if (pg_strcasecmp(prev_wd, words_after_create[i].name) == 0)
+			if (pg_strcasecmp(CAPBUF(1), words_after_create[i].name) == 0)
 			{
 				if (words_after_create[i].query)
 					COMPLETE_WITH_QUERY(words_after_create[i].query, NULL);
@@ -4164,19 +3475,10 @@ psql_completion(const char *text, int start, int end)
 #endif
 	}
 
-	/* free storage */
-	{
-		int			i;
-
-		for (i = 0; i < lengthof(previous_words); i++)
-			free(previous_words[i]);
-	}
-
 	/* Return our Grand List O' Matches */
 	return matches;
 }
 
-
 /*
  * GENERATOR FUNCTIONS
  *
@@ -4747,92 +4049,6 @@ exec_query(const char *query)
 	return result;
 }
 
-
-/*
- * Return the nwords word(s) before point.  Words are returned right to left,
- * that is, previous_words[0] gets the last word before point.
- * If we run out of words, remaining array elements are set to empty strings.
- * Each array element is filled with a malloc'd string.
- */
-static void
-get_previous_words(int point, char **previous_words, int nwords)
-{
-	const char *buf = rl_line_buffer;	/* alias */
-	int			i;
-
-	/* first we look for a non-word char before the current point */
-	for (i = point - 1; i >= 0; i--)
-		if (strchr(WORD_BREAKS, buf[i]))
-			break;
-	point = i;
-
-	while (nwords-- > 0)
-	{
-		int			start,
-					end;
-		char	   *s;
-
-		/* now find the first non-space which then constitutes the end */
-		end = -1;
-		for (i = point; i >= 0; i--)
-		{
-			if (!isspace((unsigned char) buf[i]))
-			{
-				end = i;
-				break;
-			}
-		}
-
-		/*
-		 * If no end found we return an empty string, because there is no word
-		 * before the point
-		 */
-		if (end < 0)
-		{
-			point = end;
-			s = pg_strdup("");
-		}
-		else
-		{
-			/*
-			 * Otherwise we now look for the start. The start is either the
-			 * last character before any word-break character going backwards
-			 * from the end, or it's simply character 0. We also handle open
-			 * quotes and parentheses.
-			 */
-			bool		inquotes = false;
-			int			parentheses = 0;
-
-			for (start = end; start > 0; start--)
-			{
-				if (buf[start] == '"')
-					inquotes = !inquotes;
-				if (!inquotes)
-				{
-					if (buf[start] == ')')
-						parentheses++;
-					else if (buf[start] == '(')
-					{
-						if (--parentheses <= 0)
-							break;
-					}
-					else if (parentheses == 0 &&
-							 strchr(WORD_BREAKS, buf[start - 1]))
-						break;
-				}
-			}
-
-			point = start - 1;
-
-			/* make a copy of chars from start to end inclusive */
-			s = pg_malloc(end - start + 2);
-			strlcpy(s, &buf[start], end - start + 2);
-		}
-
-		*previous_words++ = s;
-	}
-}
-
 /*
  * Look up the type for the GUC variable with the passed name.
  *
@@ -4909,4 +4125,451 @@ dequote_file_name(char *text, char quote_char)
 }
 #endif   /* NOT_USED */
 
+/* Element regular expressions */
+#define WB0  "[\\t\\n@$><=;|&{\\(\\) ]"			/* WORD BREAKS */
+#define NWB0 "[^\\t\\n@$><=;|&{\\(\\) ]"		/* ^WORD BREAKS */
+#define WB  "[\\t\\n@$><=;|&{ ]"				/* WORD BREAKS  - "()"*/
+#define WB2  "[\\t\\n@$><;|&{ ]"				/* WORD BREAKS  - "()="*/
+#define NWB "[^\\t\\n@$><=;|&{ ]"				/* ^(WORD BREAKS - "()") */
+#define PB  "^(?:.*;)?\\s*"			/* bind to the beginning of the line */
+#define PM  "^(?:.*"NWB0 WB0")?\\s*"					/* floating head */
+#define ID  NWB0"+"									/* identifier */
+#define KWD "\\w+"									/* any keywords */
+#define PSIZE_IS_64 (sizeof(void*) == 8)
+
+/* See hashfun.c for details */
+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+#define final(a,b,c) \
+{ \
+  c ^= b; c -= rot(b,14); \
+  a ^= c; a -= rot(c,11); \
+  b ^= a; b -= rot(a,25); \
+  c ^= b; c -= rot(b,16); \
+  a ^= c; a -= rot(c, 4); \
+  b ^= a; b -= rot(a,14); \
+  c ^= b; c -= rot(b,24); \
+}
+
+/* See hashfunc.c for details */
+static uint32
+hash_uint32(uint32 k)
+{
+	register uint32 a,
+				b,
+				c;
+
+	a = b = c = 0x9e3779b9 + (uint32) sizeof(uint32) + 3923095;
+	a += k;
+
+	final(a, b, c);
+
+	/* report the result */
+	return c;
+}
+
+/*
+ * Calculate hash code for the *pointer* of the pattern string, not the
+ * content of it.
+ */
+static int
+pathash(char *pat)
+{
+	uint32 t = 0;
+#if SIZEOF_VOID_P == 8
+	t = hash_uint32((uint32) ((uint64) pat >> 32));
+	t ^= hash_uint32((uint32) (uint64) pat);
+#else
+	t = hash_uint32((uint32) pat);
+#endif
+	return t % RE_HASH_SIZE;
+}
+
+/* callback functions for pg_regcomp */
+static int
+tc_cancel_requested(void)
+{
+	return cancel_pressed;
+}
+
+static int
+tc_stack_too_deep(void)
+{
+	return 0;
+}
+
+static const reg_callbacks tc_regcb =
+{
+	tc_cancel_requested,
+	tc_stack_too_deep
+};
+
+/*
+ * Returns compiled regular expression for the given pattern and cflags.
+ *
+ * Converts the given pattern into regular expression and store in hash table
+ * for the first time, then returns the stored one for the same pattern.
+ *
+ * NOTE: pattern is not well-defined so it may yeild unexpected regular
+ * expression. Regular expressions is a intermediate data so it won't be
+ * stored usually but defining DEBUG_COMPRE will store them. The stored
+ * regular expressions can be examined using perl.
+ */
+#define INTBUF_LEN 4096
+static regex_t *
+patcomp(char *pat, int cflags)
+{
+	int n = pathash(pat);
+	re_hashent *ent = &re_hash[n];
+
+	/* Search for a stored entry for the pattern and cflags */
+	while (ent && ent->next &&
+		   !(ent->repat == pat && ent->cflags == cflags) )
+		ent = ent->next;
+
+	/* Create new entry if not found */
+	if (ent->repat != pat)
+	{
+		re_hashent *newent = pg_malloc(sizeof(re_hashent));
+		int ret;
+		char restr[INTBUF_LEN];			/* generated regular expression */
+		pg_wchar rewstr[INTBUF_LEN];	/* pg_regcomp requires RE in pg_wchar */
+		char *p, *rp;
+		int relen;
+		int nest_level = 1;				/* grouping nest level  */
+		int neg_nest_level = 0;			/* nest level for negative lookahead */
+		bool prev_is_ws = true;			/* previous character was white space */
+		bool no_ws = false;				/* inhibit prefixing white space */
+		bool prev_is_id = false;		/* previous item was identifier (#id)*/
+		/*
+		 * the following two strings cannot be defined as macos because the
+		 * pointers of them have significant in this function
+		 */
+		char *NORMAL_TAIL = NWB0"*$"; /* terminal string outside parens */
+		char *INPAREN_TAIL = "[^\\)]*$";/* terminal string inside parens */
+		char *tail;						/* terminal string of regexp */
+
+		Assert(ent->next == NULL);
+
+		newent->repat = pat;
+		newent->cflags = cflags;
+		newent->next = NULL;
+
+		restr[0] = 0;
+
+		/*
+		 * If the pattern is not a whole-matching, prefix an appropriate
+		 * regular expression.
+		 */
+		if (*pat != '^')
+			strcpy(restr, PM);
+		rp = restr + strlen(restr);
+		no_ws = false;
+
+		/* Loop through the given pattern */
+		for (p = pat ; *p ; p++)
+		{
+			tail = NORMAL_TAIL;
+			prev_is_id = false;
+
+			/* @ inhibits automatic white-spacing */
+			if (*p ==  '@')
+			{
+				no_ws = true;
+				p++;
+			}
+			switch (*p)
+			{
+			case '.':
+				/* .. means the stuff of a pair of parens */
+				if (strncmp(p+1, ".", 1) == 0)
+				{
+					p++;
+					strcpy(rp, "[^\\)]*");
+				}
+				else
+				{
+					/* unknown pattern. restore terminal modes then exit */
+					rl_deprep_terminal();
+					exit(1);
+				}
+				break;
+			case '#':
+				/*
+				 * #id yields a regexp matches to any identifier including
+				 * double-quotes.
+				 */
+				if (strncmp(p+1, "id", 2) == 0)
+				{
+					p += 2;
+					if (!no_ws && !prev_is_ws)
+						strcpy(rp, WB"+");
+					strcpy(rp, ID);
+					prev_is_id = true;
+					prev_is_ws = false;
+				}
+				/* #kwd matches keywords, which consists of regular word chars*/
+				else if (strncmp(p+1, "kwd", 3) == 0)
+				{
+					p += 3;
+					if (!no_ws && !prev_is_ws)
+						strcpy(rp, WB"+");
+					strcpy(rp, "\\w+");
+					prev_is_ws = false;
+				}
+				/* #nwb matches a sequence of any non-word-breaking chars */
+				else if (strncmp(p+1, "nwb", 3) == 0)
+				{
+					p += 3;
+					if (!no_ws && !prev_is_ws)
+						strcpy(rp, WB"+");
+					strcpy(rp, NWB"+");
+					prev_is_ws = false;
+				}
+				/* #nsp matches a sequence of any non-whitespaces */
+				else if (strncmp(p+1, "nsp", 3) == 0)
+				{
+					p += 3;
+					strcpy(rp, "[^ ]*");
+					prev_is_ws = false;
+				}
+				/*  #? matches literally a '?' */
+				else if (strncmp(p+1, "?", 1) == 0)
+				{
+					p += 1;
+					strcpy(rp, "\\?");
+					prev_is_ws = true;
+				}
+				else
+				{
+					/* unknown pattern. restore terminal modes then exit */
+					rl_deprep_terminal();
+					exit(1);
+				}
+				break;
+			case '^':
+				/* force prefix matching in a statement */
+				strcpy(rp, PB);
+				prev_is_ws = true;
+				break;
+			case ' ':
+				/* add a white space, if necessary or requested by @ */
+				if (!no_ws && !prev_is_ws)
+					strcpy(rp, WB"+");
+				prev_is_ws = true;
+				break;
+			case '(':
+				/* ( means literally an open paren  */
+				strcpy(rp, WB"*\\(");
+				prev_is_ws = true;
+				tail = INPAREN_TAIL;
+				break;
+			case ')':
+				/* ) means literally a close paren */
+				strcpy(rp, "\\)"WB"*");
+				prev_is_ws = true;
+				break;
+			case '%':
+				/* % inhibits suffix matching. this is used to filter the same
+                   kind of commands. */
+				tail = "";
+				break;
+			case '|':
+			case '?':
+			case '*':
+			case '+':
+				/* these characters have the same as regular expression */
+				rp[0] = *p;
+				rp[1] = 0;
+				break;
+			case '{':
+				/* { opens non-capturing group */
+				strcpy(rp, "(?:");
+				nest_level++;
+				break;
+			case '[':
+				/* [ opens capturing group */
+				strcpy(rp, "(");
+				nest_level++;
+				break;
+			case '}':
+			case ']':
+				/* closing groups. close negative lookahead if needed */
+				if (nest_level-- == neg_nest_level)
+				{
+					strcpy(rp, ")" NWB "+");
+					while(*rp) rp++;
+					neg_nest_level = 0;
+				}
+				strcpy(rp, ")");
+				break;
+			case '!':
+				/*
+				 * ! means negative lookahead. This is a bit a complex than
+				 * other elements. This group will be closed automatically by
+				 * some conditions. One is a space, and the another is closing
+				 * of outer parens.
+				 */
+				strcpy(rp, "(?!");
+				neg_nest_level = nest_level;
+				break;
+			default:
+				if (*p)
+				{
+					if (*p == '=')
+					{
+						/* Treat this as a word, not a character */
+						if (!no_ws && !prev_is_ws && neg_nest_level > 0)
+						{
+							strcpy(rp, WB"*");
+							while(*rp) rp++;
+						}
+						
+						strcpy(rp, "=");
+						while(*rp) rp++;
+					}
+					else
+					{
+						/* loop through a literal word */
+						do {
+							if (*p == '\\')
+							{
+								/* backslashes are treated literally in a
+								 * word */
+								strcpy(rp, "\\\\");
+								rp += 2;
+								p++;
+								prev_is_ws = false;
+							}
+							else if(*p == '_')
+							{
+								/* underscore means white space in word, which
+								 * is usable for multi-word token or so */
+								strcpy(rp, WB"+");
+								while(*rp) rp++;
+								p++;
+								prev_is_ws = true;
+							}
+							else if(isalnum(*p))
+							{
+								*rp++ = *p++;
+								prev_is_ws = false;
+							}
+							else
+								break;	/* end of a word. break this loop */
+						} while (1);
+						*rp = 0;
+						p--;
+					}
+				}
+
+				/* Close negative lookahread if no alternative successives */
+				if (neg_nest_level == nest_level &&
+					(p[1] == ' ' || p[1] == 0))
+				{
+					strcpy(rp, ")" NWB "+");
+					neg_nest_level = 0;
+				}
+			}
+
+			no_ws = false;
+			while (*rp) rp++;
+		}
+
+		/*
+		 * A special treat. If pattern ends with '?', forciblly add white space
+		 */
+		if (!no_ws && (!prev_is_ws || p[-1] == '?') && tail == NORMAL_TAIL)
+		{
+			if (prev_is_id)
+				strcpy(rp, WB2"+");
+			else
+				strcpy(rp, WB2"*");
+			while (*rp) rp++;
+		}
+		strcpy(rp, tail);
+
+		/* now we have a regular expression to use */
+#ifdef DEBUG_COMPRE
+		newent->restr = strdup(restr);
+#endif		
+		relen = pg_ascii2wchar_with_len(restr, rewstr, strlen(restr));
+
+		/* disable longjump while compiling. this enable */
+		sigint_interrupt_enabled = false;
+		ret = pg_regcomp(&newent->re, rewstr, relen, cflags,
+						 C_COLLATION_OID, &tc_regcb);
+		sigint_interrupt_enabled = true;
+		if (ret != 0)
+		{
+			char	errstr[100];
+
+				pg_regerror(ret, &newent->re, errstr, sizeof(errstr));
+				fprintf(stderr, "Failed to compile regular expression(%s): %s : /%s/\n",
+						errstr, pat, restr);
+
+			/* exit immediately for the case other than cancel */
+			if (ret != REG_CANCEL)
+			{
+				rl_deprep_terminal();
+				exit(1);
+			}
+
+			/* compilation has been cancled by interrupt.  */
+			pg_free(newent);
+			newent = NULL;
+
+		}
+		ent->next = newent;
+		ent = newent;
+	}
+
+	return (ent ? &ent->re : NULL);
+}
+
+/* Apply given patterns to line buffer */
+bool
+rematch(pg_wchar *line, int linelen, char *pat, regmatch_t *rmatches,
+		int cflags)
+{
+	int ret;
+	regex_t *re;
+
+	/* immediately return failure if already stopped */
+	if (regmatch_stopped)
+		return 1;
+
+	re = patcomp(pat, cflags);
+
+	/* don't regmatch after this if this patcomp has been canceled */
+	if (!re)
+	{
+		regmatch_stopped = true;
+		return 1;
+	}
+
+	ret = pg_regexec(re, line, linelen, 0, NULL, MATCHNUM, rmatches, 0);
+
+	return ret == 0;
+}
+
+#ifdef DEBUG_COMPRE
+void dump_regexp(void);
+void
+dump_regexp(void)
+{
+	int i;
+
+	for (i = 0 ; i < RE_HASH_SIZE ; i++)
+	{
+		re_hashent *p = re_hash + i;
+
+		while (p) {
+			if (p->repat)
+				fprintf(stderr, "%03d: \"%s\" : /%s/\n", i, p->repat, p->restr);
+			p = p->next;
+		}
+	}
+}
+#endif /* DEBUG_COMPRE */
+
 #endif   /* USE_READLINE */
-- 
1.8.3.1

