Improved code-completion logic