RebalanceWhitespaceCommand.cpp [plain text]
#include "config.h"
#include "RebalanceWhitespaceCommand.h"
#include "Document.h"
#include "htmlediting.h"
#include "TextIterator.h"
#include <wtf/Assertions.h>
namespace WebCore {
RebalanceWhitespaceCommand::RebalanceWhitespaceCommand(Document *document, const Position &pos)
: EditCommand(document), m_position(pos), m_upstreamOffset(InvalidOffset)
{
}
static inline bool isWhitespace(UChar c)
{
return c == 0xa0 || isCollapsibleWhitespace(c);
}
void RebalanceWhitespaceCommand::doApply()
{
if (m_position.isNull() || !m_position.node()->isTextNode())
return;
Text* textNode = static_cast<Text*>(m_position.node());
String text = textNode->data();
ASSERT(!text.isEmpty());
ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
int offset = m_position.offset();
if (!isWhitespace(text[offset])) {
offset--;
if (offset < 0 || !isWhitespace(text[offset]))
return;
}
int upstream = offset;
while (upstream > 0 && isWhitespace(text[upstream - 1]))
upstream--;
m_upstreamOffset = upstream;
int downstream = offset;
while ((unsigned)downstream + 1 < text.length() && isWhitespace(text[downstream + 1]))
downstream++;
int length = downstream - upstream + 1;
ASSERT(length > 0);
m_beforeString = text.substring(upstream, length);
rebalanceWhitespaceInTextNode(textNode, upstream, length);
m_afterString = text.substring(upstream, length);
}
void RebalanceWhitespaceCommand::doUnapply()
{
if (m_upstreamOffset == InvalidOffset)
return;
ASSERT(m_position.node()->isTextNode());
Text* node = static_cast<Text*>(m_position.node());
ExceptionCode ec = 0;
node->deleteData(m_upstreamOffset, m_afterString.length(), ec);
ASSERT(!ec);
node->insertData(m_upstreamOffset, m_beforeString, ec);
ASSERT(!ec);
}
bool RebalanceWhitespaceCommand::preservesTypingStyle() const
{
return true;
}
}