[Tex/LaTex] Text Wrapping in tikz node doesn’t work

tikz-pgf

I would like have a few fixed nodes of size 1cm x 1cm.
However, the text inside these nodes should wrap around.

I used the following questions help to figure out about wrapping text.
However it doesn't seem to work.

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[node distance=1.75cm,auto   , font=\small]

\tikzstyle{block}=[draw, fill=white, text width=1cm, anchor=west,  minimum height=1cm]

 \node [block] [minimum width=1.5cm, minimum height=1.5cm,align=center] (mb0) {MB};
 \node [block] [right of=mb0] (dmem0) {dmem};
 \node [block] [left of=mb0] (imem0) {imem};
 \node [block] [below of=mb0,align=left] (cmemin0) {cmem\_in};
 \node [block] [right of=cmemin0] (dma0) {DMA};
 \node [block] [right of=dma0] (cmemout0) {cmem\_out};

\end{tikzpicture}
\end{document}

However you can see in the picture that the text flows outside the box
instead of wrapping around.
enter image description here

How do I resolve this situation?

Thanks !

Best Answer

So, several problems are stacking in your case.

First, the hyphenation engine cannot guess what is a correct hyphenation for a word like cmem_in. I am not even sure there is such a correct hyphenation.

In this case, you need to marks the points where the break is allowed with \-.

Second, even for "not so strange" words, like "averylonglongstring", the hyphenation does not happen. The reason is given in this question: the first word of a paragraph is not hyphenated by design.

A suggested workaround is to use \hspace{0pt} before such words. Note that in the MWE, longstring still flows out of the box, that's because it is a "strange word" again.

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[node distance=1.75cm,auto   , font=\small]

  \tikzstyle{block}=[draw, fill=white, text width=1cm, anchor=west,  minimum height=1cm]

  \node [block] [minimum width=1.5cm, minimum height=1.5cm,align=center] (mb0) {MB};
  \node [block] [right of=mb0] (dmem0) {dmem};
  \node [block] [left of=mb0,align=left] (imem0) {averylonglongstring};
  \node [block] [below of=mb0,align=left] (cmemin0) {cmem\-\_in};
  \node [block] [right of=cmemin0,align=left] (dma0) {\hspace{0pt}averylonglongstring};
  \node [block] [right of=dma0,align=left,text width=1.5cm] (cmemout0) {cmem\-\_out};

\end{tikzpicture}
\end{document}

enter image description here