You might also be interested in how comint deals with this. It can handle the case when the user yanks something in the middle of output as well. See function comint--mark-as-output, bug#3735 and bug#18135 for more details.