1 #----------------------------------------------------------------------
2 # Name: wx.lib.wordwrap
3 # Purpose: Contains a function to aid in word-wrapping some text
8 # RCS-ID: $Id: wordwrap.py 54718 2008-07-19 18:57:26Z RD $
9 # Copyright: (c) 2006 by Total Control Software
10 # Licence: wxWindows license
11 #----------------------------------------------------------------------
13 def wordwrap(text
, width
, dc
, breakLongWords
=True, margin
=0):
15 Returns a copy of text with newline characters inserted where long
16 lines should be broken such that they will fit within the given
17 width, with the given margin left and right, on the given `wx.DC`
18 using its current font settings. By default words that are wider
19 than the margin-adjusted width will be broken at the nearest
20 character boundary, but this can be disabled by passing ``False``
21 for the ``breakLongWords`` parameter.
25 text
= text
.split('\n')
27 pte
= dc
.GetPartialTextExtents(line
)
28 wid
= ( width
- (2*margin
+1)*dc
.GetTextExtent(' ')[0]
29 - max([0] + [pte
[i
]-pte
[i
-1] for i
in range(1,len(pte
))]) )
35 # remember the last seen space
39 # have we reached the max width?
40 if pte
[idx
] - start
> wid
and (spcIdx
!= -1 or breakLongWords
):
43 wrapped_lines
.append(' '*margin
+ line
[startIdx
: idx
] + ' '*margin
)
50 wrapped_lines
.append(' '*margin
+ line
[startIdx
: idx
] + ' '*margin
)
52 return '\n'.join(wrapped_lines
)
56 if __name__
== '__main__':
58 class TestPanel(wx
.Panel
):
59 def __init__(self
, parent
):
60 wx
.Panel
.__init
__(self
, parent
)
62 self
.tc
= wx
.TextCtrl(self
, -1, "", (20,20), (150,150), wx
.TE_MULTILINE
)
63 self
.Bind(wx
.EVT_TEXT
, self
.OnDoUpdate
, self
.tc
)
64 self
.Bind(wx
.EVT_SIZE
, self
.OnSize
)
67 def OnSize(self
, evt
):
68 wx
.CallAfter(self
.OnDoUpdate
, None)
71 def OnDoUpdate(self
, evt
):
72 WIDTH
= self
.GetSize().width
- 220
74 bmp
= wx
.EmptyBitmap(WIDTH
, HEIGHT
)
75 mdc
= wx
.MemoryDC(bmp
)
76 mdc
.SetBackground(wx
.Brush("white"))
78 mdc
.SetPen(wx
.Pen("black"))
79 mdc
.SetFont(wx
.Font(10, wx
.SWISS
, wx
.NORMAL
, wx
.NORMAL
))
80 mdc
.DrawRectangle(0,0, WIDTH
, HEIGHT
)
82 text
= wordwrap(self
.tc
.GetValue(), WIDTH
-2, mdc
, False)
84 mdc
.DrawLabel(text
, (1,1, WIDTH
-2, HEIGHT
-2))
87 dc
= wx
.ClientDC(self
)
88 dc
.DrawBitmap(bmp
, 200, 20)
92 frm
= wx
.Frame(None, title
="Test wordWrap")