void (@NotNull Document document, int offset, @NotNull CharSequence s) { try { document.insertString(offset, s); } catch (ReadOnlyFragmentModificationException ex) { String blockPrefix = document.getImmutableCharSequence().subSequence(ex.getGuardedBlock().getStartOffset(), offset).toString(); if (!blockPrefix.isEmpty() && s.toString().endsWith(blockPrefix)) { int newOffset = offset - blockPrefix.length(); String newString = blockPrefix + s.subSequence(0, s.length() - blockPrefix.length()); insertString(document, newOffset, newString); } else { throw ex; } } }