[Sage] Improve autocomplete handling and fix some segfaults
(cherry picked from commit 9f69b4df41c3c63f5d25daa966888d9d78060f32)