如何在org.eclipse.xtext.ui.editor.embedded.EmbeddedEditor中显示120字符处打印边距竖线?
Great question! The org.eclipse.xtext.ui.editor.embedded.EmbeddedEditor doesn’t expose a direct, dedicated API for setting a print margin (that vertical line at a specific character column) out of the box, but you absolutely can implement this by tapping into its underlying SWT components. Here’s how to do it:
Step 1: Access the underlying StyledText widget
The EmbeddedEditor relies on Eclipse’s ISourceViewer for text rendering, which in turn uses a StyledText widget (the core SWT component for text display). You can retrieve this widget with a few simple calls:
// Assume you have an initialized EmbeddedEditor instance EmbeddedEditor embeddedEditor = ...; // Get the source viewer from the embedded editor ISourceViewer sourceViewer = embeddedEditor.getViewer(); // Extract the underlying StyledText widget StyledText styledText = (StyledText) sourceViewer.getTextWidget();
Step 2: Set the print margin column
The StyledText widget has native support for print margins. Use its setPrintMarginColumn(int) method to set the margin at the 120-character position. You can also explicitly ensure the margin is visible (it’s enabled by default, but being explicit avoids unexpected behavior):
// Set the print margin to 120 characters styledText.setPrintMarginColumn(120); // Ensure the margin is visible (optional but recommended) styledText.setPrintMarginVisible(true);
Important Notes
- Timing matters: Run this code only after the
EmbeddedEditorhas been fully initialized and added to its parent container. If you try to access theStyledTexttoo early (before the editor is rendered), it might returnnull. - Font dependency: The column value is based on the average character width of the widget’s current font. SWT automatically calculates the correct pixel position for the margin line, so you don’t need to handle manual pixel conversions.
- Instance-specific setting: This change applies only to your specific
EmbeddedEditorinstance, not to other Xtext or Eclipse editors. It won’t be affected by the user’s global Eclipse print margin preferences.
This approach leverages the SWT infrastructure that Xtext’s EmbeddedEditor builds on, making it a reliable way to add the print margin you need.
内容的提问来源于stack exchange,提问作者user3561614

