How to do search and replace involving fields in Microsoft Word? - ms-word

I have a Word document with fields of the reference variety, which occur in the form "[field].[field]"--in other words, there's a period between the two fields. I want to globally replace this with a space.
Word offers the ^d special character to search for fields, but for some reason the query "^d.^d" does not find anything. However, ".^d" does. Now comes the problem, however--what do I specify as the replacement text in order to retain the field code? If using regular expressions, I could use a "Find What Expression" such as \1, but with regexp ("wild card") mode the ^d is not permitted.
I guess I could write a macro...

I would like to add to Bibadia's solution.
An example of an index entry field; we want to change a name we misspelled.
Make sure hidden formatting is displayed (toggle with SHIFT+CTRL+F8).
Make sure wildcards option is not selected. To search for fields, use the opening and closing field braces code (optionally use ^w for spaces, as Bibadia suggested):^19 XE "Deo, John" ^21
Replace won't recognize field braces character, but will allow to insert the clipboard's content. ;). To do that, insert in text the correct entry. CTRL+F9 to insert field and type:XE "Doe, John"
Select the field above and copy
Use ^c in the replace box
Hit Replace All
Ta-da!

It's usually better to go the macro route when finding fields because, as you say, the find algorithm that Word uses doesn't work the way you might hope with fields.
But if you know exactly what the fields contain, you can specify a search pattern that will probably work (however not in wildcard mode).
For example, if you want to look for figure number field pairs such as
{ STYLEREF 1 \s }.{ SEQ Figure \* ARABIC \s 1 }
(which would typically be the same set of fields everywhere in the document)
If you only really need to look for the following:
{ STYLEREF 1 \s }.<any field>
you could ensure that field codes are displayed and search for
^d STYLEREF 1 \s ^21.^d
or
^19 STYLEREF 1 \s ^21.^19
If you need to be more precise, you can spell out the second field as well.
"^d" only works for finding the field beginning, not the field end.
It's a shame that ^w wants to find at least 1 whitespace character because otherwise it would be more robust to look for
^19^wSTYLEREF^w1^w\s^w^21.^19
Perhaps someone else knows how to work around that without using wildcards?

Torzaburo,
I suggest that you do this using a macro. You can start by recording the macro, and later refining your processing steps within the macro.
First turn on the hidden characters by navigating to Home > Paragraph > toggle the show/hide Paragraph symbol. Also, select all and toggle the field codes on (right-click and select "Toggle Field Codes".
Open a new blank Word doc in addition to the one you have open. You will use this later. Start the macro recording and find the field using the "^d" (field code) as you said.
When the field is found, copy only the field text within the brackets, and not the full field reference. While the macro is still recording, ALT + TAB to the new blank document and paste the field code in as plain text.
At this point, do the necessary find & replace processing to the field codes. Highlight the processed field codes, copy, ALT + TAB back to the original document, and paste back between the { } brackets.
Stop the macro recording. Add any further custom processing to the macro VBA.
Select-All and re-toggle the field codes. Update the field codes.

You don't need a macro. Just toggle all field codes on by using Alt+F9. Then do a find and replace for what you want to change. Once the replacement is complete, use Alt+F9 again to toggle the field codes back off.

Disclaimer: I didn't originate this solution, but it's clean and elegant and I thought it should be included here:
(Adapted from Search & Replace Field Codes in Word):
Create or find a single instance of the field you want to convert text to
Toggle Field Codes visible (AltF9)
Copy the code for the field you want to use to the Clipboard (highlight and CtrlC)
Open the Replace dialog box (CtrlH), insert the text you want to replace in the Find What box and then enter ^c in the Replace With box.
This will replace your text with the contents of the Clipboard, turning it into the field code you copied in step 3. It also copies formatting information (font, color, etc.), to control how the field will appear when hidden. (Caveat: I've tested this with Word 2003 under Windows 7 only.)

Coming in late on this, probably way too late for Beth (sorry Beth). And this may not be quite what Beth was looking for. But for anyone interested ...
It sounds like Beth may have created captions throughout the document using INSERT CAPTION (hence the presence of field codes). This means these captions will have been (automatically) created in CAPTION style.
To globally replace the separator "." with " " (space) in such captions, take two steps:
[1] Go to REFERENCES | INSERT CAPTION, then click on NUMBERING and replace the SEPARATOR "." with "EM-DASH". This will replace all separators in captions for the selected label in the CAPTION Window. If you have other labels in use in the document (e.g. FIGURE), select the other labels one by one and repeat this process.
[2] Do a find/replace searching for special character "em-dash" (^+) in style CAPTION, replacing with " ". Click REPLACE ALL.
Voila!
NOTE: This presumes that em-dash does not appear in the caption text anywhere. If it does, then you'll need to do a pre- and post- "fiddle" to ensure these em-dashes are not touched by the global replace above.
The "pre-fiddle" is to do a global find/replace across captions, replacing the em-dash ("^+") with some other string (e.g. "EM-DASH") that doesn't ever occur in any caption's text. Then you do the separator change as described above. Finally, the "post-fiddle" is to restore the em-dashes that were in the captions, by doing a global replace of the string "EM-DASH" with the actual em-dash character "^+".

Related

Multiline regular expression search in Visual Studio Code

Multiline regular expression search doesn't work in VS Code version 1.27.2 .
Theoretically aaa(\n|.)*bbb should find string starting from aaa and ending bbb but it doesn't work.
The solution mentioned here Multi-line regular expressions in Visual Studio Code doesn't work as well.
Multiline search is added in v1.29 released in November 2018. See multi-line search.
VS Code now supports multiline search! Same as in the editor, a regex
search executes in multiline mode only if it contains a \n literal.
The Search view shows a hint next to each multiline match, with the
number of additional match lines.
This feature is possible thanks to the work done in the ripgrep tool
to implement multiline search.
Multiline search is coming to the Find Widget with v1.38. See multiline find "pre-release" notes.
Multi Line search in Find Widget
The Find Widget now supports multiple line text search and replace. By
pressing Ctrl+Enter, you can insert new lines into the input box.
.
Odd that it is Ctrl+Enter in the Find Widget but Shift+Enter in the Search Panel (see Deepu's answer below). Shift+Enter has other functionality when the Find Widget is focused.
yes, you could use regex for mutliple line search in VScode.
To find a multi-line text block starting from aaa and ending with the first bbb (lazy qualifier)
aaa(.|\n)+?bbb
To find a multi-line text block starting from aaa and ending with the last bbb. (greedy qualifier)
aaa(.|\n)+bbb
I have been looking for a quick way to do this, and I have come to the following:
start_text.*?(.|[\n])*?end_text
with start_text and end_text being the bounds of your multiline search.
breaking down the regex ".?(.|[\n])?":
".?" will match any characters from your start text to the end of the line. The "?" is there to ensure that if your end_text is on the same line the . wont just keep going to the end of the line regardless (greedy vs lazy matching)
"(.|[\n])" means either a character\whitespace or a new line
"*?" specifies to match 0 or more of the expression in the parentheses without being greedy.
Examples:
<meta.*?(.|[\n])*?/> will match from the beginning of all meta tags to the end of the respective tags
<script.*?(.|[\n])*?</script> will match from the beginning of all script tags to the respective closing tags
Warning:
Using .*?(.|[\n])*? with improperly or partially filled in start_text or end_text might crash VS Code. I suggest either writing the whole expression out (which doesn't cause a problem) or writing the start and end text before pasting in the regex. In any case, when I tried to delete parts of the starting and ending text VS Code froze and forced me to reload the file. That being said, I honestly could not find something that worked better in VS Code.
Without using regex.
Multi-line search is now possible in vs code version 1.30 and above without using regex.
Type Shift+Enter in the search box to insert a newline, and the search box will grow to show your full multiline query. You can also copy and paste a multiline selection from the editor into the search box.
You can find and replace in multiple lines by using this simple regex : StringStart\r\nStringEnd
For example
public string MethodA(int x)
{
var user;
}
public string MethodB(string y)
{
var user;
}
public string MethodC(int x)
{
var user;
}
public string MethodD(float x)
{
var user;
}
If you want to replace the name of user variable with customer along with method parameter name to user but only for the int ones.
Then the regex to find will be : int x)\r\nEnterBlankSpacesHereToReachTheString{\r\nEnterBlankSpacesHereToReachTheStringvar user
and regex to replace will be : int user)\r\nEnterBlankSpacesHereToReachTheString{\r\nEnterBlankSpacesHereToReachTheStringvar customer
See for reference
I had a similar issue, this works better for me:
aaa[.\n\r\t\S\s]*bbb
This includes carriage return (\r), new line (\n), tab (\t), any whitespece (\s) and any non whitespace (\S). There seems to be some redundancy putting "." and "\S" together, but it doesn't work without both in my case.
No regex way: you can copy multiline text and paste it in "Find in files" form:
result of "Replace all":
(.|\n)+? or [\s\S\r]* or [.\n\r\t\S\s]* may be understandable when viewed in isolation, but in an already complex regex expression, they can add that extra layer of complexity that makes the whole thing unmanageable.
On Windows, for files on the local disk, I find the best solution is to switch to using Notepad++. Not only does it handle multi-line out of the box, it also has a pleasant interface for multi-file search and replace, handles macros gracefully, and is quite light-weight. You can switch back to VScode as soon you have finished your regex changes. Personally, I deleted Notepad++ when I found VScode, but reinstalled it later when I found some of what Notepad++ had to offer was missing in VScode. Both are free to use! I'm sure there's an equivalent on the Mac.
If you are willing to search JavaScript, TypeScript or JSON files I can recommend my VScode extension
It allows for formatting agnostic text search and structural code search
You can find it on codeque.co or at VSCode Marketplace
Your query could look like this
aaa$$mbbb
where $$m means optional multiline set of any characters
Make sure to use text mode for this query
CodeQue can make much more than that!
The reason on this behavior is very simple.
Multiple line search isn't implemented yet.
see: Support multi-line search for Global search

How to increase visual length of form text field in Word?

When a form text field is inserted in a Word document, the grey shaded length is about 5 characters long. How can this length be increased?
Allthough it is a rather crude measure (and I don't recommend it), you can set "Properties -> Default Text" to as many blanks as you want the size. But this comes for a price: as long as you move into the field by pressing TAB, all blanks are selected and get typed over. When you use the mouse, you click the cursor anywhere into the field and start typing ... so your entry might be pre and post fixed by a number of blanks that you have to trim away in e.g. an exit macro.
I recommend old form fields as the last resort (i.e. there must be a good reason to use them) and would prefer (in that order)
native Word2010/2007 fields (text or Rich text - perhaps not backwords compatible)
legacy ActiveX fields (compatible with W2003)
Legacy (old) form fields

How to select and modify all caption fields at once in a Word document?

I have been trying to change the numbering style of my figure and table captions. All of my headings are in Roman numerical. However, I want Arabic numerical in my caption numbering. Could anyone tell me an easy way to do it at once? Below is an example:
Heading title: "Chapter V". My captions appear as "Figure V-2". However, I want them to appear as "Figure 5-2"
Also, is there any way I can select all figure caption fields at once and edit their field code?
To change in one caption: Press Alt-F9 and remove \* ARABIC .
Ctrl+A, F9 to update fields.
Now to change in all captions: try with a search and replace (Ctrl+H) to replace SEQ Figure \* Arabic \s 1 with SEQ Figure \s 1
To modify all field codes, you could use search & replace or you can modify field codes in VBA this way:
Sub ChangeAllFields()
'does not process headers/footers
Dim oFld As Field
For Each oFld In ActiveDocument.Fields
fld.Code = Replace(fld.Code, "SEQ Figure \* ARABIC \s 1", "SEQ Figure \s 1")
Next oFld
End Sub
When you insert captions from now on, change the numbering in the dialog box that pops up. I think you'll have to change it every time, because Word (correctly) defaults to matching the Roman numerals in your chapter headings to Roman numerals in your captions. If you want to be abnormal, you'll have to change from the default every time you insert a caption, or change them all using one of the methods from Toon Flores.
p.s. I said "abnormal" because every style manual I've ever seen would frown on what you are doing.

Add Variable Hyperlink in Mail Merge in Word 2013

I'm trying to add a hyperlink to a mail merge field. So something like this:
{HYPERLINK "{MERGEFIELD "Links" }"}
So I create a field like this.
{ MERGEFIELD Links }
And the above works (it displays different links for different recipients).
However, when I go to Edit Field, and then attempt to add HYPERLINK to { MERGEFIELD Links}, Word will not allow me. Meaning that when I type HYPERLINK followed by a space, the "variable" field is gone. Instead of word displaying...
LINK
it displays...
{HYPERLINK "{MERGEFIELD "Links" }"}
even after I press "update field". So Word is not letting me enter HYPERLINK for some reason.
How do I solve this?
From the Microsoft Web Site,
On the Insert menu, click Field (under Quick Parts in later office versions).
In the Field names list, click Hyperlink,
and then click OK. The text Error! Hyperlink reference not valid
appears in the document.
Press ALT+F9 to open the { HYPERLINK \* MERGEFORMAT } field code.
Put the insertion point after HYPERLINK and then add a space.
On the Insert menu, click Field. In the Field names list, click MergeField. In the Field name text box, type the name of the data source field that contains the hyperlink, and then click OK. For example, if the name of the data source field is "Address1," the field code appears as follows: { HYPERLINK { MERGEFIELD "Address1" } \* MERGEFORMAT }
Press ALT+F9 to close the field code. You now have Error! Hyperlink reference not valid text.
Put the insertion point at some arbitrary place in the middle of the Error! Hyperlink reference not valid text, and insert the text you want to appear. If you would like a merge field, insert that from the "Insert Merge Field" option on the menu.
Delete the remaining text of Error! ... before and after the text you want to keep.
Note: If your merge field only contains an identifier, with the URL to be provided as a static part of the merge document, this can work also. On Step 5, you will need to insert the URL text as well as the MergeField, for example:
{ HYPERLINK "https://www.myurl.com/EditForm.aspx?ID={ MERGEFIELD ID }" \* MERGEFORMAT }
I also have been struggling with this. What I found to be the key is creating the document from SCRATCH and not saving it before executing the mail merge. Here are the steps I used:
open a new document and click on the step by step mail merge wizard; add your generic text.
To add the variable hyperlink go to insert>quick parts>fields
select hyperlink on the left and click okay
Use alt + F9 to see the hyperlink field code
Type “” and between them insert your merged field so that {HYPERLINK \* MERGEFORMAT} -> becomes {HYPERLINK"{MERGEFIELD"Constructed_URL"}"\*MERGEFORMAT}
Press ALT+F9 to hide the field code
Click in the text "Error! Hyperlink reference not valid" and replace with something generic like click here.
Complete the mail merge BEFORE you save the document.
Hope this helps and good luck!
Start with the process here:
http://support.microsoft.com/kb/912679
However, like user1867326 indicated, the hyperlink (which should be variable with the mail merge) is converted into a static link when the Word file is reopened.
A solution that seems to work is adding a bookmark within the hyperlink field code immediatly after the mergefield.
{ HYPERLINK { MERGEFIELD "Link" } \* MERGEFORMAT }
Click between the } and \ and go to INSERT > Bookmark, give it a name, and this seems to prevent Word from replacing the mergefield with a static hyperlink.
This answer is adapted and hopefully clarified from the clever solution described here:
Mailmerge dynamic hyperlink fields lost after save/reload of document - Word 2010
This is what worked for me for an email mail merge with variable hyperlinks that all display the same text. I am using Office 2016 Word.
Put the insertion point where you would like the link display text to be in the document.
On the Insert menu, click Quick Parts, and select Field.
In the Field Names list, click Hyperlink, and then click OK. The text Error! Hyperlink reference not valid appears in the document.
Press ALT+F9 to open the { HYPERLINK * MERGEFORMAT } field code. 5. Put the insertion point after HYPERLINK.
On the Insert menu, click Quick Parts, and select Field. In the Field Names list, click MergeField.
In the Field name text box, type the name of the data source field that contains the hyperlink, and then click OK. For example, if the name of the data source field is "Address1," the field code appears as follows: { HYPERLINK { MERGEFIELD Address1 } * MERGEFORMAT }
Press ALT+F9 to close the field code. You now have Error! Hyperlink reference not valid text.
Put the insertion point just before the period in ‘Error! Hyperlink reference not valid text.’ and delete all the text except for the period. Write in the link display text. Make sure not to delete the period (this is important).
To check that the hyperlinks are mapping, right click on the link display text and click edit hyperlink. You will see the correct link in the address field for each record.
I like to style the period text color to white so it looks invisible.
I have had limited success with the other suggestions - basically, Word is buggy in this area. There is a simple alternative - indeed the only alternative AKAIK if you want the hyperlink to vary AND the text that is displayed to vary too (not an unreasonable requirement).
Note that this only works for DOCUMENT MERGES, not for EMAIL MERGES, since it relies on processesing the output document.
The trick is to add a place marker (text that serves as an ID) wherever you want a hyperlink. Insert this via a regular mergefield. In your table of source data, you need columns
place marker, text_for_display, hyperlink
You then need to put your source data into Excel (if that isn't where you have it already) and put this formula
="Set Rng = ActiveDocument.Content: Rng.Find.Execute FindText:="""&[place marker]&""": ActiveDocument.Hyperlinks.Add Anchor:=Rng, Address:="""&[hyperlink]&""", TextToDisplay:="""&[text_for_display]&""""
into a blank column in the first row, and fill down.
You need to amend [place marker],[hyperlink] and [text_for_display] to the appropriate cell references.
If the [hyperlink] includes a query string, you may find you want to build it using a formula, based on other data in the source.
The resulting formulae can then be pasted into a macro and run on the output document.
You may then want to use the "Robbins/Mayor" macro http://www.wordbanter.com/showthread.php?t=18346 to split the generated documents.
I got this working thanks to this thread, but then it stopped working and I figured out why so I thought I'd say thanks by posting what I discovered here.
The issue is that word has a special type of curly brace. Copying the code text from this thread may not work for that reason. To get the curly braces Word wants, I used Fn + Command + F9 on my Mac running Catalina and Office 365. Apparently some Mac users may find Command + F9 works -- just test to find out. I'm sure Windows has a similar keystroke set. I found the Mac solution in this post.
Also, the syntax that works for me is: { HYPERLINK { MERGEFIELD "url" } * MERGEFORMAT } where "url" is the label of the column with the link in my Excel file. Note the position of the quotes. This differs from other posts here (I tried the other combinations) but I wouldn't be surprised if the syntax may vary across Word versions and operating systems.
To get this method to work in Mac Office 365 (Big Sur), you need to know about the Toggle Field Codes in the context menu. The shortcut above to replicate the Alt-F9 behavior will create a new field, instead of allowing you to edit the field that exists.
At these steps:
Press ALT+F9 to open the { HYPERLINK * MERGEFORMAT } field code.
OR
Press ALT+F9 to close the field code. You now have Error! Hyperlink reference not valid text.
Instead of the keyboard shortcut, right click on the error message and select Toggle Field Codes from the context menu.
Answer worked great for me with this adjustment! Thank you!

Can I make a macro in n++ that does a search/replace?

I'm new to n++, but I have been most impressed with this tool so far. I've been trying to record a macro that do a search/replace, but the 'search' part seems to have the initial search text from the recording 'hard-coded' in the macro.
What I want is:
Manually locate the cursor at the beginning of the first line of a fixed format code segment, then Macro actions:
move cursor two lines down
move cursor right x characters
mark charters from pos x to x+n
search and replace all occurrences of the selected text with "{p_'selected text'}"
In an more advanced version, I'd like to add some logic to step 4: only execute the replace part if the # of occurrences are > 1 (e.g. by first adding a count statement, but I'm not sure how to obtain the returned count # from the dialog box)
Is this possible?
While I'm a big fan of Notepad++, this sounds like something I would accomplish with AutoHotKey. You would select the text and copy it to the clipboard. AutoHotKey would read the clipboard, replace the text as you desire, and either replace the clipboard contents, or send it back to your document. Let me know if you would like to go that route.