R8.2: Word EQ fields open as formulas; inline objects follow their run

Gitea #9. Patch 0049 moves inline pictures and OLE objects with
their run's w:position. Patches 0050 and 0051 turn EQ fields into
Math objects; unreadable fields show their code. Round 3 findings
(lowercase \s\do tail, split subscripts, \ai/\di, italics through
OMML) fixed and covered by word.rs; no fourth review.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude committed 2026-10-18 21:39:17 -04:00
1 parent 6f1eebb4b5
commit 2ca53ef585
11 files changed
+975 -1

No files matched your search

@@ -0,0 +1,199 @@
Writer: an inline object moves with its run's w:position
Word lowers or raises an inline picture or OLE object with the
w:position of its run; MathType equations rely on it to sit on
the baseline (Gitea #9: 25 pictures and an OLE fraction stood
above their lines). The import kept w:position as a deferred
character property and applied it to text only, so an object's
run lost it.
The import now puts the position on the object's anchor
character, as a fixed escapement against that character's own
font size, and does not expand it to the text after. Layout
moves an as-character object by its anchor character's fixed
escapement (vertAlign's automatic values keep objects still,
as before). Every export already writes the anchor character's
escapement (w:position in DOCX), so the position round-trips.
The w:position arithmetic moves into one helper both use.
--- a/sw/source/core/inc/ascharanchoredobjectposition.hxx
+++ b/sw/source/core/inc/ascharanchoredobjectposition.hxx
@@ -86,6 +86,9 @@ namespace objectpositioning
// method to cast <SwAnchoredObjectPosition::GetAnchorFrame()>
const SwTextFrame& GetAnchorTextFrame() const;
+ // the anchor character's fixed raise
+ SwTwips GetRaise() const;
+
/** determine the relative position to base line for object position
@param _ObjBoundHeight
--- a/sw/source/core/objectpositioning/ascharanchoredobjectposition.cxx
+++ b/sw/source/core/objectpositioning/ascharanchoredobjectposition.cxx
@@ -29,6 +29,11 @@
#include <editeng/ulspitem.hxx>
#include <osl/diagnose.h>
#include <fmtornt.hxx>
+#include <fmtanchr.hxx>
+#include <ndtxt.hxx>
+#include <hintids.hxx>
+#include <editeng/escapementitem.hxx>
+#include <editeng/fhgtitem.hxx>
using namespace ::com::sun::star;
@@ -60,6 +65,23 @@ SwAsCharAnchoredObjectPosition::SwAsCharAnchoredObjectPosition(
SwAsCharAnchoredObjectPosition::~SwAsCharAnchoredObjectPosition()
{}
+/** the anchor character's fixed raise */
+SwTwips SwAsCharAnchoredObjectPosition::GetRaise() const
+{
+ const SwPosition* pAnchor = GetFrameFormat().GetAnchor().GetContentAnchor();
+ const SwTextNode* pNode = pAnchor ? pAnchor->GetNode().GetTextNode() : nullptr;
+ if (!pNode)
+ return 0;
+ SfxItemSetFixed<RES_CHRATR_ESCAPEMENT, RES_CHRATR_FONTSIZE> aSet(
+ const_cast<SwAttrPool&>(pNode->GetDoc().GetAttrPool()));
+ const sal_Int32 nIndex = pAnchor->GetContentIndex();
+ pNode->GetParaAttr(aSet, nIndex, nIndex + 1);
+ const short nEsc = aSet.Get(RES_CHRATR_ESCAPEMENT).GetEsc();
+ if (nEsc == DFLT_ESC_AUTO_SUPER || nEsc == DFLT_ESC_AUTO_SUB)
+ return 0;
+ return SwTwips(aSet.Get(RES_CHRATR_FONTSIZE).GetHeight()) * nEsc / 100;
+}
+
/** method to cast <SwAnchoredObjectPosition::GetAnchorFrame()> to needed type */
const SwTextFrame& SwAsCharAnchoredObjectPosition::GetAnchorTextFrame() const
{
@@ -162,7 +184,8 @@ void SwAsCharAnchoredObjectPosition::CalcPosition()
const SwTwips nObjBoundHeight = ( mnFlags & AsCharFlags::Rotate )
? aObjBoundRect.Width()
: aObjBoundRect.Height();
- const SwTwips nRelPos = GetRelPosToBase( nObjBoundHeight, rVert );
+ // it moves with its raised character, as in Word
+ const SwTwips nRelPos = GetRelPosToBase( nObjBoundHeight, rVert ) - GetRaise();
// for initial positioning:
// adjust the proposed anchor position by difference between
--- a/sw/source/writerfilter/dmapper/DomainMapper.cxx
+++ b/sw/source/writerfilter/dmapper/DomainMapper.cxx
@@ -3979,26 +3979,11 @@ void DomainMapper::processDeferredCharacterProperties(
{
case NS_ooxml::LN_EG_RPrBase_position:
{
- double nEscapement = 0;
- sal_Int8 nProp = 0;
- if ( nIntValue )
- {
- nProp = 100;
- double fFontSize = 0;
- m_pImpl->GetAnyProperty(PROP_CHAR_HEIGHT, rContext) >>= fFontSize;
- if ( fFontSize )
- // nIntValue is in half-points, fontsize is in points, escapement is a percentage.
- nEscapement = round( nIntValue/2.0 / fFontSize * 100 );
- else
- nEscapement = nIntValue > 0 ? DFLT_ESC_SUPER : DFLT_ESC_SUB;
- }
- if ( nEscapement > MAX_ESC_POS )
- nEscapement = MAX_ESC_POS;
- else if ( nEscapement < -MAX_ESC_POS )
- nEscapement = -MAX_ESC_POS;
-
- rContext->Insert(PROP_CHAR_ESCAPEMENT, uno::Any( sal_Int16(nEscapement) ) );
- rContext->Insert(PROP_CHAR_ESCAPEMENT_HEIGHT, uno::Any( nProp ) );
+ double fFontSize = 0;
+ m_pImpl->GetAnyProperty(PROP_CHAR_HEIGHT, rContext) >>= fFontSize;
+ const sal_Int16 nEscapement = DomainMapper_Impl::GetPositionEscapement(nIntValue, fFontSize);
+ rContext->Insert(PROP_CHAR_ESCAPEMENT, uno::Any( nEscapement ) );
+ rContext->Insert(PROP_CHAR_ESCAPEMENT_HEIGHT, uno::Any( sal_Int8(nIntValue ? 100 : 0) ) );
}
break;
default:
--- a/sw/source/writerfilter/dmapper/DomainMapper_Impl.hxx
+++ b/sw/source/writerfilter/dmapper/DomainMapper_Impl.hxx
@@ -345,6 +345,7 @@ public:
const css::uno::Reference<css::text::XTextRange>& GetStartRange() const { return m_xStartRange; }
void AppendCommand(std::u16string_view rPart);
+ /// Deleted command text has no look.
const OUString& GetCommand() const {return m_sCommand[m_bCommandType]; }
bool GetCommandIsEmpty(bool bType) const { return m_sCommand[bType].isEmpty(); }
void SetCommandType(bool cType) { m_bCommandType = cType; }
@@ -839,6 +840,10 @@ public:
void MergeAtContentImageRedlineWithNext(const css::uno::Reference<css::text::XTextAppend>& xTextAppend);
void appendTextPortion( const OUString& rString, const PropertyMapPtr& pPropertyMap );
void appendTextContent(const css::uno::Reference<css::text::XTextContent>&, const css::uno::Sequence<css::beans::PropertyValue>&);
+ /// w:position's half-points as an escapement percentage.
+ static sal_Int16 GetPositionEscapement(sal_Int32 nHalfPoints, double fFontSize);
+ /// Word moves an inline object with its run's w:position.
+ void moveWithRun(const css::uno::Reference<css::text::XTextContent>& xContent);
void appendOLE( const OUString& rStreamName, const std::shared_ptr<OLEHandler>& pOleHandler );
void appendStarMath( const Value& v);
void adjustLastPara(sal_Int8 nAlign);
--- a/sw/source/writerfilter/dmapper/DomainMapper_Impl.cxx
+++ b/sw/source/writerfilter/dmapper/DomainMapper_Impl.cxx
@@ -135,6 +135,13 @@
#include <docufld.hxx>
#include <txtfld.hxx>
#include <ndtxt.hxx>
+#include <doc.hxx>
+#include <fmtanchr.hxx>
+#include <frmfmt.hxx>
+#include <IDocumentContentOperations.hxx>
+#include <editeng/escapementitem.hxx>
+#include <editeng/fhgtitem.hxx>
+#include <hintids.hxx>
#include <unicode/errorcode.h>
#include <unicode/regex.h>
#include <unotextcursor.hxx>
@@ -3652,6 +3659,7 @@ void DomainMapper_Impl::appendTextContent(
xTextAppendAndConvert->insertTextContentWithProperties( xContent, xPropertyValues, m_aTextAppendStack.top().xInsertPosition );
else
xTextAppendAndConvert->appendTextContent( xContent, xPropertyValues );
+ moveWithRun(xContent);
}
catch(const lang::IllegalArgumentException&)
{
@@ -3661,6 +3669,41 @@ void DomainMapper_Impl::appendTextContent(
}
}
+sal_Int16 DomainMapper_Impl::GetPositionEscapement(sal_Int32 nHalfPoints, double fFontSize)
+{
+ if (!nHalfPoints)
+ return 0;
+ // half-points against the font size in points, as a percentage
+ double fEscapement = fFontSize ? round(nHalfPoints / 2.0 / fFontSize * 100)
+ : nHalfPoints > 0 ? DFLT_ESC_SUPER : DFLT_ESC_SUB;
+ return sal_Int16(std::clamp<double>(fEscapement, -MAX_ESC_POS, MAX_ESC_POS));
+}
+
+void DomainMapper_Impl::moveWithRun(const uno::Reference<text::XTextContent>& xContent)
+{
+ auto& rDeferred = m_StreamStateStack.top().deferredCharacterProperties;
+ auto it = rDeferred.find(NS_ooxml::LN_EG_RPrBase_position);
+ if (it == rDeferred.end())
+ return;
+ SwXFrame* pFrame = dynamic_cast<SwXFrame*>(xContent.get());
+ SwFrameFormat* pFormat = pFrame ? pFrame->GetFrameFormat() : nullptr;
+ if (!pFormat || pFormat->GetAnchor().GetAnchorId() != RndStdIds::FLY_AS_CHAR)
+ return;
+ // the anchor character carries the raise
+ SwPaM aChar(*pFormat->GetAnchor().GetContentAnchor());
+ aChar.SetMark();
+ aChar.GetPoint()->AdjustContent(1);
+ // a percentage of the anchor character's own size
+ SfxItemSetFixed<RES_CHRATR_FONTSIZE, RES_CHRATR_FONTSIZE> aSize(aChar.GetDoc().GetAttrPool());
+ aChar.GetPointNode().GetTextNode()->GetParaAttr(aSize, aChar.Start()->GetContentIndex(), aChar.End()->GetContentIndex());
+ const sal_Int16 nEsc = GetPositionEscapement(it->second.get<sal_Int32>(), aSize.Get(RES_CHRATR_FONTSIZE).GetHeight() / 20.0);
+ if (!nEsc)
+ return;
+ // the run's text after it keeps its own position
+ aChar.GetDoc().getIDocumentContentOperations().InsertPoolItem(
+ aChar, SvxEscapementItem(nEsc, 100, RES_CHRATR_ESCAPEMENT), SetAttrMode::DONTEXPAND);
+}
+
void DomainMapper_Impl::appendOLE( const OUString& rStreamName, const std::shared_ptr<OLEHandler>& pOLEHandler )
{
try
@@ -0,0 +1,454 @@
Writer: read Word EQ field commands as StarMath
A parser for Word EQ field commands: \f fraction, \r radical,
\s super- and subscript, \b brackets, \l list, \a array,
\i integral, sum and product; \x and \o keep their content
without the box or overlay, \d moves forward only; \ai and
\di only space lines. Switches ignore case, as Word reads them.
Each command character keeps its vertAlign; one script stays one
script across style changes. Italic letters become identifiers,
which StarMath and OMML both draw italic. The next patch uses it.
--- a/sw/Library_sw_writerfilter.mk
+++ b/sw/Library_sw_writerfilter.mk
@@ -89,6 +89,7 @@ $(eval $(call gb_Library_add_exception_objects,sw_writerfilter,\
sw/source/writerfilter/dmapper/DomainMapperTableHandler \
sw/source/writerfilter/dmapper/DomainMapperTableManager \
sw/source/writerfilter/dmapper/DomainMapper_Impl \
+ sw/source/writerfilter/dmapper/EqField \
sw/source/writerfilter/dmapper/domainmapperfactory \
sw/source/writerfilter/dmapper/FFDataHandler \
sw/source/writerfilter/dmapper/FontTable \
--- /dev/null
+++ b/sw/source/writerfilter/dmapper/EqField.hxx
@@ -0,0 +1,30 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+#pragma once
+
+#include <rtl/ustring.hxx>
+
+#include <vector>
+
+namespace writerfilter::dmapper
+{
+/// How one character of a field command looks.
+struct EqLook
+{
+ bool bItalic = false;
+ /// -1 subscript, 0 baseline, 1 superscript.
+ sal_Int8 nScript = 0;
+};
+
+/// A Word EQ field as StarMath; empty if unreadable.
+OUString EqToStarMath(std::u16string_view rCommand, const std::vector<EqLook>& rLooks);
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
--- /dev/null
+++ b/sw/source/writerfilter/dmapper/EqField.cxx
@@ -0,0 +1,397 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+#include "EqField.hxx"
+
+#include <rtl/character.hxx>
+#include <rtl/ustrbuf.hxx>
+#include <sal/log.hxx>
+#include <unicode/uchar.h>
+
+#include <map>
+
+namespace writerfilter::dmapper
+{
+namespace
+{
+/// Word's EQ switches as StarMath.
+class EqParser
+{
+ std::u16string_view m_aCommand;
+ const std::vector<EqLook>& m_rLooks;
+ size_t m_nPos = 0;
+ bool m_bFailed = false;
+
+public:
+ EqParser(std::u16string_view aCommand, const std::vector<EqLook>& rLooks)
+ : m_aCommand(aCommand)
+ , m_rLooks(rLooks)
+ {
+ }
+
+ OUString parse()
+ {
+ skipSpaces();
+ if (rtl::toAsciiLowerCase(at(m_nPos)) != 'e' || rtl::toAsciiLowerCase(at(m_nPos + 1)) != 'q')
+ return OUString();
+ m_nPos += 2;
+ skipSpaces();
+ OUString aMath = element(false);
+ return m_bFailed ? OUString() : aMath;
+ }
+
+private:
+ sal_Unicode at(size_t nPos) const { return nPos < m_aCommand.size() ? m_aCommand[nPos] : 0; }
+
+ EqLook look(size_t nPos) const { return nPos < m_rLooks.size() ? m_rLooks[nPos] : EqLook(); }
+
+ void skipSpaces()
+ {
+ while (at(m_nPos) == ' ')
+ ++m_nPos;
+ }
+
+ void fail(const char* pWhy)
+ {
+ SAL_WARN("writerfilter.dmapper", "EQ field: " << pWhy << " at " << m_nPos);
+ m_bFailed = true;
+ }
+
+ static OUString quoted(std::u16string_view aText)
+ {
+ OUStringBuffer aBuf("\"");
+ for (sal_Unicode c : aText)
+ {
+ if (c == '"')
+ aBuf.append('\\');
+ aBuf.append(c);
+ }
+ return aBuf.append('"').makeStringAndClear();
+ }
+
+ /// Italic letters as identifiers, which OMML keeps italic.
+ static void italic(std::vector<OUString>& rRuns, std::u16string_view aText)
+ {
+ OUStringBuffer aOther;
+ auto other = [&]() {
+ if (!aOther.isEmpty())
+ rRuns.push_back("ital " + quoted(aOther.makeStringAndClear()));
+ };
+ for (sal_Unicode c : aText)
+ {
+ if (!u_isalpha(c))
+ {
+ aOther.append(c);
+ continue;
+ }
+ other();
+ rRuns.push_back(OUString(c));
+ }
+ other();
+ }
+
+ /// A bracket character's StarMath name; empty if unknown.
+ static OUString brace(sal_Unicode c, bool bLeft)
+ {
+ static const std::map<sal_Unicode, OUString> aNames{
+ { '(', u"("_ustr }, { ')', u")"_ustr }, { '[', u"["_ustr },
+ { ']', u"]"_ustr }, { '{', u"lbrace"_ustr }, { '}', u"rbrace"_ustr },
+ { '<', u"langle"_ustr }, { '>', u"rangle"_ustr }, { 0x27E8, u"langle"_ustr },
+ { 0x27E9, u"rangle"_ustr }, { 0x230A, u"lfloor"_ustr }, { 0x230B, u"rfloor"_ustr },
+ { 0x2308, u"lceil"_ustr }, { 0x2309, u"rceil"_ustr }
+ };
+ if (c == '|')
+ return bLeft ? u"lline"_ustr : u"rline"_ustr;
+ if (c == 0x2016)
+ return bLeft ? u"ldline"_ustr : u"rdline"_ustr;
+ auto it = aNames.find(c);
+ return it == aNames.end() ? OUString() : it->second;
+ }
+
+ /// A big operator character's StarMath name; empty if unknown.
+ static OUString bigOperator(sal_Unicode c)
+ {
+ static const std::map<sal_Unicode, OUString> aNames{
+ { 0x2211, u"sum"_ustr }, { 0x220F, u"prod"_ustr }, { 0x2210, u"coprod"_ustr },
+ { 0x222B, u"int"_ustr }, { 0x222C, u"iint"_ustr }, { 0x222D, u"iiint"_ustr },
+ { 0x222E, u"lint"_ustr }, { 0x222F, u"llint"_ustr }, { 0x2230, u"lllint"_ustr }
+ };
+ auto it = aNames.find(c);
+ return it == aNames.end() ? OUString() : it->second;
+ }
+
+ /// Puts `aScript` above or below the last atom.
+ static void attach(std::vector<OUString>& rAtoms, sal_Int8 nScript, const OUString& aScript)
+ {
+ // empty text, not a placeholder
+ OUString aBase = u"\"\""_ustr;
+ if (!rAtoms.empty())
+ {
+ aBase = "{" + rAtoms.back() + "}";
+ rAtoms.pop_back();
+ }
+ rAtoms.push_back(aBase + (nScript > 0 ? u"^{" : u"_{") + aScript + "}");
+ }
+
+ /// Text up to an argument's end, or all.
+ OUString element(bool bArgument)
+ {
+ std::vector<OUString> aAtoms;
+ // runs that share one script position
+ std::vector<OUString> aGroup;
+ OUStringBuffer aText;
+ EqLook aLook;
+ auto piece = [&]() {
+ if (aText.isEmpty())
+ return;
+ OUString aRun = aText.makeStringAndClear();
+ if (aLook.bItalic)
+ italic(aGroup, aRun);
+ else
+ aGroup.push_back(quoted(aRun));
+ };
+ auto flush = [&]() {
+ piece();
+ if (aGroup.empty())
+ return;
+ if (aLook.nScript == 0)
+ aAtoms.insert(aAtoms.end(), aGroup.begin(), aGroup.end());
+ else
+ {
+ OUStringBuffer aScript;
+ for (const OUString& rRun : aGroup)
+ aScript.append((aScript.isEmpty() ? u"" : u" ") + rRun);
+ attach(aAtoms, aLook.nScript, aScript.makeStringAndClear());
+ }
+ aGroup.clear();
+ };
+ auto add = [&](sal_Unicode c, EqLook aNew) {
+ if (aNew.nScript != aLook.nScript)
+ flush();
+ else if (aNew.bItalic != aLook.bItalic)
+ piece();
+ aLook = aNew;
+ aText.append(c);
+ };
+ int nDepth = 0;
+ while (m_nPos < m_aCommand.size() && !m_bFailed)
+ {
+ sal_Unicode c = m_aCommand[m_nPos];
+ if (bArgument && nDepth == 0 && (c == ',' || c == ')'))
+ break;
+ if (c == '\\')
+ {
+ sal_Unicode cNext = at(m_nPos + 1);
+ // general switches such as \* MERGEFORMAT follow the equation
+ if (!bArgument && nDepth == 0
+ && (cNext == '*' || cNext == '#' || cNext == '@' || cNext == '!'))
+ {
+ while (!aText.isEmpty() && aText[aText.getLength() - 1] == ' ')
+ aText.setLength(aText.getLength() - 1);
+ break;
+ }
+ if (rtl::isAsciiAlpha(cNext))
+ {
+ flush();
+ ++m_nPos;
+ command(aAtoms);
+ continue;
+ }
+ if (cNext != 0)
+ {
+ add(cNext, look(m_nPos + 1));
+ m_nPos += 2;
+ continue;
+ }
+ }
+ if (c == '(')
+ ++nDepth;
+ else if (c == ')')
+ --nDepth;
+ add(c, look(m_nPos));
+ ++m_nPos;
+ }
+ flush();
+ OUStringBuffer aMath;
+ for (const OUString& rAtom : aAtoms)
+ aMath.append((aMath.isEmpty() ? u"" : u" ") + rAtom);
+ return aMath.makeStringAndClear();
+ }
+
+ /// `(e, e, ...)`.
+ std::vector<OUString> arguments()
+ {
+ std::vector<OUString> aArgs;
+ skipSpaces();
+ if (at(m_nPos) != '(')
+ {
+ fail("no arguments");
+ return aArgs;
+ }
+ ++m_nPos;
+ while (!m_bFailed)
+ {
+ aArgs.push_back(element(true));
+ sal_Unicode c = at(m_nPos++);
+ if (c == ')')
+ break;
+ if (c != ',')
+ fail("unclosed arguments");
+ }
+ return aArgs;
+ }
+
+ /// The switch after `\`, its options and arguments.
+ void command(std::vector<OUString>& rAtoms)
+ {
+ const sal_Unicode cCommand = rtl::toAsciiLowerCase(m_aCommand[m_nPos++]);
+ std::map<OUString, OUString> aOptions;
+ for (skipSpaces(); at(m_nPos) == '\\' && rtl::isAsciiAlpha(at(m_nPos + 1)); skipSpaces())
+ {
+ // switches ignore case, as Word reads them
+ OUString aName = OUString(m_aCommand.substr(m_nPos + 1, 2)).toAsciiLowerCase();
+ m_nPos += 3;
+ if (aName == "lc" || aName == "rc" || aName == "bc" || aName == "fc" || aName == "vc")
+ {
+ if (at(m_nPos) == '\\')
+ ++m_nPos;
+ aOptions[aName] = OUString(at(m_nPos++));
+ continue;
+ }
+ skipSpaces();
+ size_t nStart = m_nPos;
+ while (rtl::isAsciiDigit(at(m_nPos)))
+ ++m_nPos;
+ aOptions[aName] = OUString(m_aCommand.substr(nStart, m_nPos - nStart));
+ }
+ std::vector<OUString> aArgs = arguments();
+ if (m_bFailed)
+ return;
+ auto join = [&](std::u16string_view aBetween) {
+ OUStringBuffer aBuf;
+ for (size_t i = 0; i < aArgs.size(); ++i)
+ aBuf.append((i ? aBetween : u"") + OUString("{" + aArgs[i] + "}"));
+ return aBuf.makeStringAndClear();
+ };
+ switch (cCommand)
+ {
+ case 'f':
+ if (aArgs.size() != 2)
+ return fail("a fraction needs two parts");
+ rAtoms.push_back("{" + aArgs[0] + "} over {" + aArgs[1] + "}");
+ break;
+ case 'r':
+ if (aArgs.size() == 1)
+ rAtoms.push_back("sqrt{" + aArgs[0] + "}");
+ else if (aArgs.size() == 2)
+ rAtoms.push_back("nroot{" + aArgs[0] + "}{" + aArgs[1] + "}");
+ else
+ return fail("a radical needs one or two parts");
+ break;
+ case 's':
+ // \ai and \di only add line spacing
+ if (aOptions.contains(u"up"_ustr))
+ attach(rAtoms, 1, join(u" "));
+ else if (aOptions.contains(u"do"_ustr))
+ attach(rAtoms, -1, join(u" "));
+ else
+ rAtoms.push_back("stack{" + join(u" # ") + "}");
+ break;
+ case 'b':
+ {
+ static const std::map<sal_Unicode, sal_Unicode> aClosing{
+ { '(', ')' }, { '[', ']' }, { '{', '}' }, { '<', '>' }
+ };
+ auto option = [&](const OUString& rKey) {
+ auto it = aOptions.find(rKey);
+ return it == aOptions.end() || it->second.isEmpty() ? sal_Unicode(0)
+ : it->second[0];
+ };
+ const sal_Unicode cBoth = option(u"bc"_ustr);
+ sal_Unicode cLeft = option(u"lc"_ustr);
+ sal_Unicode cRight = option(u"rc"_ustr);
+ if (!cLeft)
+ cLeft = cBoth ? cBoth : '(';
+ if (!cRight)
+ {
+ auto it = aClosing.find(cBoth);
+ cRight = !cBoth ? ')' : it != aClosing.end() ? it->second : cBoth;
+ }
+ const OUString aLeft = brace(cLeft, true);
+ const OUString aRight = brace(cRight, false);
+ if (aLeft.isEmpty() || aRight.isEmpty())
+ return fail("an unknown bracket");
+ rAtoms.push_back("left " + aLeft + " " + join(u" \",\" ") + " right " + aRight);
+ break;
+ }
+ case 'l':
+ rAtoms.push_back(join(u" \",\" "));
+ break;
+ case 'a':
+ {
+ sal_Int32 nColumns = std::max<sal_Int32>(1, aOptions[u"co"_ustr].toInt32());
+ OUString aAlign = aOptions.contains(u"al"_ustr) ? u"alignl "_ustr
+ : aOptions.contains(u"ar"_ustr) ? u"alignr "_ustr
+ : OUString();
+ // a short last row is padded, never dropped
+ while (aArgs.size() % nColumns)
+ aArgs.emplace_back();
+ OUStringBuffer aBuf("matrix{");
+ for (size_t i = 0; i < aArgs.size(); ++i)
+ {
+ if (i)
+ aBuf.append(i % nColumns ? u" # " : u" ## ");
+ aBuf.append(aAlign + "{" + aArgs[i] + "}");
+ }
+ rAtoms.push_back(aBuf.append("}").makeStringAndClear());
+ break;
+ }
+ case 'i':
+ {
+ if (aArgs.size() != 3)
+ return fail("an integral needs three parts");
+ OUString aOperator = aOptions.contains(u"su"_ustr) ? u"sum"_ustr
+ : aOptions.contains(u"pr"_ustr) ? u"prod"_ustr
+ : u"int"_ustr;
+ // a given operator character wins
+ for (const OUString& rKey : { u"fc"_ustr, u"vc"_ustr })
+ {
+ auto it = aOptions.find(rKey);
+ if (it == aOptions.end())
+ continue;
+ aOperator = it->second.isEmpty() ? OUString() : bigOperator(it->second[0]);
+ if (aOperator.isEmpty())
+ return fail("an unknown operator");
+ }
+ rAtoms.push_back(aOperator + " from{" + aArgs[0] + "} to{" + aArgs[1] + "} {"
+ + aArgs[2] + "}");
+ break;
+ }
+ case 'x':
+ case 'o':
+ rAtoms.push_back(join(u" "));
+ break;
+ case 'd':
+ if (aOptions.contains(u"fo"_ustr))
+ rAtoms.push_back(u"~"_ustr);
+ break;
+ default:
+ fail("an unknown switch");
+ }
+ }
+};
+}
+
+OUString EqToStarMath(std::u16string_view rCommand, const std::vector<EqLook>& rLooks)
+{
+ return EqParser(rCommand, rLooks).parse();
+}
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
@@ -0,0 +1,169 @@
Writer: Word EQ fields open as formulas
DOCX import read only EQ's \o, \s\do and ruby forms; every other
EQ field, such as \f(a,b) for a fraction, vanished (Gitea #9).
The import now turns an EQ field into a Math object through
the parser of the previous patch. Each command character keeps
its run's italic and vertAlign, as Word draws them (a with a
subscript 10 is a_{10}); the formula takes the field's font
size. A command the parser cannot read shows its field code as
text, so nothing vanishes and the failure stays visible. Only a
whole plain \s\do N(text) field stays lowered text, as before;
the old reader dropped anything after its first bracket.
--- a/sw/source/writerfilter/dmapper/DomainMapper_Impl.hxx
+++ b/sw/source/writerfilter/dmapper/DomainMapper_Impl.hxx
@@ -26,6 +26,7 @@
#include <com/sun/star/style/TabStop.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/embed/XStorage.hpp>
+#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <queue>
#include <stack>
#include <string_view>
@@ -50,6 +51,7 @@
#include "ThemeHandler.hxx"
#include "GraphicImport.hxx"
#include "OLEHandler.hxx"
+#include "EqField.hxx"
#include "FFDataHandler.hxx"
#include "SmartTagHandler.hxx"
#include "FormControlHelper.hxx"
@@ -303,6 +305,8 @@ class FieldContext : public virtual SvRefBase
// 0: Normal, inserted command line
// 1: Deleted command line
OUString m_sCommand[2];
+ /// The look of each inserted command character, for EQ fields.
+ std::vector<EqLook> m_aCommandLooks;
OUString m_sResult;
OUString m_sVariableValue;
std::optional<FieldId> m_eFieldId;
@@ -346,6 +350,12 @@ public:
void AppendCommand(std::u16string_view rPart);
/// Deleted command text has no look.
+ void AppendLooks(sal_Int32 nCount, EqLook aLook)
+ {
+ if (!m_bCommandType)
+ m_aCommandLooks.insert(m_aCommandLooks.end(), nCount, aLook);
+ }
+ const std::vector<EqLook>& GetCommandLooks() const { return m_aCommandLooks; }
const OUString& GetCommand() const {return m_sCommand[m_bCommandType]; }
bool GetCommandIsEmpty(bool bType) const { return m_sCommand[bType].isEmpty(); }
void SetCommandType(bool cType) { m_bCommandType = cType; }
@@ -846,6 +856,9 @@ public:
void moveWithRun(const css::uno::Reference<css::text::XTextContent>& xContent);
void appendOLE( const OUString& rStreamName, const std::shared_ptr<OLEHandler>& pOleHandler );
void appendStarMath( const Value& v);
+ void appendFormula(const css::uno::Reference<css::embed::XEmbeddedObject>& xFormula);
+ /// A Word EQ field as a formula object.
+ void appendEqFormula(const FieldContextPtr& pContext);
void adjustLastPara(sal_Int8 nAlign);
rtl::Reference<SwXTextSection> appendTextSectionAfter(css::uno::Reference<css::text::XTextRange> const & xBefore);
--- a/sw/source/writerfilter/dmapper/DomainMapper_Impl.cxx
+++ b/sw/source/writerfilter/dmapper/DomainMapper_Impl.cxx
@@ -92,6 +92,9 @@
#include <com/sun/star/document/XImporter.hpp>
#include <com/sun/star/document/XFilter.hpp>
#include <comphelper/indexedpropertyvalues.hxx>
+#include <comphelper/classids.hxx>
+#include <comphelper/embeddedobjectcontainer.hxx>
+#include <tools/globname.hxx>
#include <editeng/flditem.hxx>
#include <editeng/unotext.hxx>
#include <o3tl/deleter.hxx>
@@ -3815,19 +3818,44 @@ void DomainMapper_Impl::appendOLE( const OUString& rStreamName, const std::share
}
+void DomainMapper_Impl::appendEqFormula(const FieldContextPtr& pContext)
+{
+ // the looks index the untrimmed command
+ const OUString aMath = EqToStarMath(pContext->GetCommand(), pContext->GetCommandLooks());
+ if (aMath.isEmpty())
+ {
+ // an unreadable field shows its code, never vanishes
+ appendTextPortion(pContext->GetCommand().trim(), pContext->getProperties());
+ return;
+ }
+ comphelper::EmbeddedObjectContainer aContainer;
+ OUString aName;
+ uno::Reference<embed::XEmbeddedObject> xFormula = aContainer.CreateEmbeddedObject(
+ SvGlobalName(SO3_SM_CLASSID).GetByteSequence(), aName, m_aBaseUrl);
+ uno::Reference<beans::XPropertySet> xMath(xFormula->getComponent(), uno::UNO_QUERY_THROW);
+ xMath->setPropertyValue(u"Formula"_ustr, uno::Any(aMath));
+ double fHeight = 0;
+ if (GetAnyProperty(PROP_CHAR_HEIGHT, pContext->getProperties()) >>= fHeight)
+ xMath->setPropertyValue(u"BaseFontHeight"_ustr, uno::Any(sal_Int16(std::round(fHeight))));
+ appendFormula(xFormula);
+}
+
void DomainMapper_Impl::appendStarMath( const Value& val )
{
uno::Reference< embed::XEmbeddedObject > formula;
val.getAny() >>= formula;
- if( !formula.is() )
- return;
+ if( formula.is() )
+ appendFormula(formula);
+}
+void DomainMapper_Impl::appendFormula(const uno::Reference<embed::XEmbeddedObject>& formula)
+{
try
{
rtl::Reference<SwXTextEmbeddedObject> xStarMath = m_xTextDocument->createTextEmbeddedObject();
xStarMath->setPropertyValue(getPropertyName( PROP_EMBEDDED_OBJECT ),
- val.getAny());
+ uno::Any(formula));
// tdf#66405: set zero margins for embedded object
xStarMath->setPropertyValue(getPropertyName( PROP_LEFT_MARGIN ),
uno::Any(sal_Int32(0)));
@@ -6599,11 +6627,20 @@ void DomainMapper_Impl::AppendFieldCommand(OUString const & rPartOfCommand)
{
// Set command line type: normal or deleted
pContext->SetCommandType(m_bTextDeleted);
+ PropertyMapPtr pCharContext = GetTopContextOfType(CONTEXT_CHARACTER);
if (pContext->GetCommand().isEmpty())
{
- pContext->getProperties()->InsertProps(GetTopContextOfType(CONTEXT_CHARACTER));
+ pContext->getProperties()->InsertProps(pCharContext);
}
pContext->AppendCommand( rPartOfCommand );
+ EqLook aLook;
+ awt::FontSlant eSlant = awt::FontSlant_NONE;
+ aLook.bItalic = (GetAnyProperty(PROP_CHAR_POSTURE, pCharContext) >>= eSlant)
+ && eSlant == awt::FontSlant_ITALIC;
+ sal_Int16 nEscapement = 0;
+ GetAnyProperty(PROP_CHAR_ESCAPEMENT, pCharContext) >>= nEscapement;
+ aLook.nScript = nEscapement > 0 ? 1 : nEscapement < 0 ? -1 : 0;
+ pContext->AppendLooks(rPartOfCommand.getLength(), aLook);
}
}
@@ -8209,7 +8246,13 @@ void DomainMapper_Impl::CloseFieldCommand()
sal_Int32 nSpaceIndex = aCommand.indexOf(' ');
if(nSpaceIndex > 0)
aCommand = o3tl::trim(aCommand.subView(nSpaceIndex));
- if (aCommand.startsWith("\\s"))
+ // only a whole plain lowered run stays text
+ sal_Int32 nOpen = aCommand.indexOf('(');
+ bool bLowered = aCommand.startsWith("\\s\\do") && nOpen > 0
+ && aCommand.indexOf(')') == aCommand.getLength() - 1
+ && aCommand.indexOf('(', nOpen + 1) < 0
+ && aCommand.indexOf('\\', 5) < 0;
+ if (bLowered)
{
aCommand = aCommand.copy(2);
if (aCommand.startsWith("\\do"))
@@ -8236,6 +8279,8 @@ void DomainMapper_Impl::CloseFieldCommand()
{
handleRubyEQField(pContext);
}
+ else
+ appendEqFormula(pContext);
}
}
break;