sortLinesWithRegion :: Region -> BufferM ()
sortLinesWithRegion region = modifyExtendedLRegion region (onLines sort')
    where sort' [] = []
          sort' lns =
              if hasnl (last lns)
                  then sort lns
                  else over _last
                      -- should be completely safe since every element contains newline
                      (fromMaybe (error "sortLinesWithRegion fromMaybe") . R.init) . sort $
                          over _last (`R.snoc` '\n') lns
          hasnl t | R.last t == Just '\n' = True
                  | otherwise = False

-- | Helper function: revert the buffer contents to its on-disk version
sortLinesWithRegion :: Region -> BufferM ()
sortLinesWithRegion region = modifyExtendedLRegion region (onLines sort')
    where sort' [] = []
          sort' lns =
              if hasnl (last lns)
                  then sort lns
                  else over _last
                      -- should be completely safe since every element contains newline
                      (fromMaybe (error "sortLinesWithRegion fromMaybe") . R.init) . sort $
                          over _last (`R.snoc` '\n') lns
          hasnl t | R.last t == Just '\n' = True
                  | otherwise = False

-- | Helper function: revert the buffer contents to its on-disk version
sortLinesWithRegion region = modifyExtendedLRegion region (onLines sort')
    where sort' [] = []
          sort' lns =
              if hasnl (last lns)
                  then sort lns
                  else over _last
                      -- should be completely safe since every element contains newline
                      (fromMaybe (error "sortLinesWithRegion fromMaybe") . R.init) . sort $
                          over _last (`R.snoc` '\n') lns
          hasnl t | R.last t == Just '\n' = True
                  | otherwise = False

-- | Helper function: revert the buffer contents to its on-disk version