[pmwiki-users] text replace using regex in edit textarea
Petko Yotov
5ko at 5ko.fr
Fri Jan 23 09:36:59 PST 2026
I would reuse the core JavaScript GUIEdit functions and the PmLib
helpers available since PmWiki 2.4.0 (latest recommended).
Create a file, say pub/myrxreplace.js, and put in it something like
this:
PmLib.ready(function(){
const { dqs, dce, adjbe, tap } = PmLib; // import helpers
const container = dqs('span.GUIButtons');
if(!container) return;
const button = dce('input', {type:'button', value:'RXR'});
adjbe(container, button); // add before the end of GUIButtons
function replace_in_selection(selection) {
if(selection==='') return '';
let result = selection
.replace(/\r\n?/g, "\n") // normalize line breaks
.replace(/ *(\n *)+/g, ' ') // join lines
.replace(/pmwiki/ig, 'PmWiki') // fix capitalization
// add your own
;
return result;
}
tap(button, function(){ // onclick
insMarkup(replace_in_selection);
});
});
Enable this script in local/config.php, assumes $EnableGUIButtons is
enabled:
if($action=='edit') $HTMLHeaderFmt['myrxreplace']
= '<script src="$PubDirUrl/myrxreplace.js"></script>';
The "const button..." part is the button added to the end of the GUI
buttons container. The value 'RXR' is the button label, obviously you
can change it, or even use an emoji.
Select some text in the edit textarea and click on the button. This will
cause the function replace_in_selection() to be called with argument the
current selection text. It should make the replacements and changes,
then return the result which will be inserted in place of the selection
in the edit textarea.
I would also enable $EnablePreviewChanges = 1; and press "Preview" to
see my changes before saving the page.
Using the built-in helper functions is much simpler and easier than
doing it in plain JavaScript, you don't need to locate the textarea,
detect the selection, handle undo/redo, sync with PmSyntax, everything
works under the hood.
Petko
--
If you upgrade : https://www.pmwiki.org/Upgrades
On 23/01/2026 17:07, Hans Bracker wrote:
> Hi Petko, I am wondering if there is a way to add a custom guibutton
> and/or keyboard shortcut to do a custom text replace on a text
> selection in the standard edit textarea?
>
> I would like to select some text in the edit textarea, like a
> paragraph, or more, from a longer page text, and then via a button
> click or a keyboard shortcut have a regular expression replace done on
> this text. In particular I like to strip out newline \n and replace
> with simple space, to undo formatting from inserted pdf text. I can do
> this in my code editor, but copying and pasting paragraphs back and
> forward is a hassle. Ideally I like to choose the regular expression,
> or set up different custom "regex text replace" buttons.
>
> I don't know if i need to hack the guiedit javascript, or how to add
> the functionality in javascript. Some advice would be greatly
> appreciated!
More information about the pmwiki-users
mailing list