diff --git a/src/Text/Pandoc/Writers/GridTable.hs b/src/Text/Pandoc/Writers/GridTable.hs index 529b2fad7..a005f0eb7 100644 --- a/src/Text/Pandoc/Writers/GridTable.hs +++ b/src/Text/Pandoc/Writers/GridTable.hs @@ -124,17 +124,29 @@ rowsToPart attr = \case forM_ cells $ \(Cell cellAttr align rs cs blks) -> do ridx' <- readSTRef ridx let nextFreeInRow colindex@(ColIndex c) = do - readArray grid (ridx', colindex) >>= \case - FreeCell -> pure colindex - _ -> nextFreeInRow $ ColIndex (c + 1) - cidx' <- readSTRef cidx >>= nextFreeInRow - writeArray grid (ridx', cidx') . FilledCell $ - ContentCell cellAttr align rs cs blks - forM_ (continuationIndices ridx' cidx' rs cs) $ \idx -> do - writeArray grid idx . FilledCell $ - ContinuationCell (ridx', cidx') - -- go to new column - writeSTRef cidx cidx' + let idx = (ridx', colindex) + if gbounds `inRange` idx + then readArray grid idx >>= \case + FreeCell -> pure (Just colindex) + _ -> nextFreeInRow $ ColIndex (c + 1) + else pure Nothing -- invalid table + mcidx' <- readSTRef cidx >>= nextFreeInRow + -- If there is a FreeCell in the current row, then fill it + -- with the current cell and mark cells in this and the + -- following rows as continuation cells if necessary. + -- + -- Just skip the current table cell if no FreeCell was + -- found; this can only happen with invalid tables. + case mcidx' of + Nothing -> pure () -- no FreeCell left in row -- skip cell + Just cidx' -> do + writeArray grid (ridx', cidx') . FilledCell $ + ContentCell cellAttr align rs cs blks + forM_ (continuationIndices ridx' cidx' rs cs) $ \idx -> do + writeArray grid idx . FilledCell $ + ContinuationCell (ridx', cidx') + -- go to new column + writeSTRef cidx cidx' -- go to next row modifySTRef ridx (incrRowIndex 1) -- Swap BuilderCells with normal GridCells.