Hack 39 Apply Context-Sensitive Formatting
Which character style you apply to a selection of text may depend on its context. This hack makes it easy to apply the correct one of several similar styles by using a macro to examine the selection''s surroundings. A complex document template may have several similar character styles, each fulfilling a different semantic purpose in the document''s structure. The template used for this manuscript, for example, has two styles used to emphasize portions of text: one called emphasis (used to emphasize normal body text) and the other replaceable (used to emphasize text presented in a constant-width font). Which style is used depends on the context of the text to be emphasized. One way to ensure the correct application of several different, but similar, character styles is to provide users with a detailed set of instructions about which style to use in any particular situation (and when not to use a particular style, such as in a heading). But many people will simply do what they''ve always done in Word to emphasize text: press the I button on the Formatting toolbar. Unfortunately, this action only applies direct formatting on top of the paragraph style already in use. You can try just telling people not to reach for the I button, or you can opt to intercept the Italic command [Hack #61] and apply the correct character style based on the current paragraph style. For example, assume that there are two character styles, emphasis and replaceable, governed by the following four rules:
Do not apply character styles with multiple paragraphs selected.
Do not use character styles in headings.
If the paragraph style''s name includes the word "Code," use the replaceable character style.
In all other situations, use the emphasis character style. 4.14.1 The Code
The following macro examines the context of the selected text when you press the I button and then, based on the rules described above, performs one of three possible actions:
Ignores the command
Warns the user that the attempted action is not permitted
Applies one of the two character styles
After you place this macro in the template of your choice [Hack #50], it will run whenever you press the I button on the toolbar or the key command associated with italic (typically Ctrl-I):
Sub Italic( ) Dim sel As Selection Dim sParagraphStyleName As String Set sel = Selection '' Quietly exit if selection spans multiple paragraphs If sel.Range.Paragraphs.Count <> 1 Then Exit Sub '' Warn then exit if selection is in a heading sParagraphStyleName = sel.Range.Paragraphs.First.Style If InStr(sParagraphStyleName, "Heading") Then MsgBox "Sorry, Character Styles aren''t allowed in headings" Exit Sub End If '' Apply appropriate character style If InStr(sParagraphStyleName, "Code") Then sel.Style = "replaceable" Else sel.Style = "emphasis" End If End Sub
|