Win32::Mechanize::NotepadPlusPlus::Notepad - The main application object for Notepad++ automation
use Win32::Mechanize::NotepadPlusPlus ':main'; my $npp = notepad(); # main application
The editor object for Notepad++ automation using Win32::Mechanize::NotepadPlusPlus
The module was developed with Notepad++ v7.7 or newer in mind, though some features should still work on older versions of Notepad++. As Notepad++ adds new features, the minimum version for that method will be indicated in the help.
The constructors and similar object methods in this section are purely for class access, and will be called by the NotepadPlusPlus object. They should never need to be referenced directly. (Instead, you will get the notepad, editor1, editor2, and editor instances from the app instance)
notepad
editor1
editor2
editor
use Win32::Mechanize::NotepadPlusPlus; # creates the singleton ::Notepad object my $npp = Win32::Mechanize::NotepadPlusPlus::notepad(); # calls ...Notepad::notepad() my $ed1 = Win32::Mechanize::NotepadPlusPlus::editor1(); # calls ...Notepad::editor1() my $ed2 = Win32::Mechanize::NotepadPlusPlus::editor2(); # calls ...Notepad::editor2() my $ed = Win32::Mechanize::NotepadPlusPlus::editor(); # calls ...Notepad::editor()
notepad->hwnd(); my $npp_hWnd = notepad()->hwnd();
Grabs the window handle of the Notepad++ main window.
This is used for sending Windows messages; if you are enhancing the Notepad object's functionality (implementing some new Notepad++ message that hasn't made its way into this module, for example), you will likely need access to this handle.
These are the object-oriented methods for manipulating the Notepad++ GUI, using the notepad() instance.
notepad()
These methods open, close, and save files (standard File menu operations).
notepad->close();
Closes the currently active document
notepad->closeAll();
Closes all open documents
notepad->closeAllButCurrent();
Closes all but the currently active document
notepad->newFile();
Create a new document.
notepad->open($filename);
Opens the given file.
notepad->save();
Save the current file
notepad->saveAllFiles();
Saves all currently unsaved files
notepad->saveAs($filename);
Save the current file as the specified $filename
notepad->saveAsCopy($filename);
Save the current file as the specified $filename, but don’t change the filename for the buffer in Notepad++
Sessions allow you to make a group of files that you can easily reload by loading the session.
notepad->saveCurrentSession($filename);
Save the current session (list of open files) to a file.
notepad->saveSession($filename, @filesList);
Saves a session (list of filenames in @filesList) to a file.
notepad->loadSession($sessionFilename);
Opens the session by loading all the files listed in the $sessionFilename.
notepad->getSessionFiles($sessionFilename);
Reads the session stored in $sessionFilename, and returns a list of the file paths that it references.
This does not open the files in the session; to do that, use notepad()->loadSession($sessionFilename)
notepad()->loadSession($sessionFilename)
These methods influence which views are available and which file buffers are available in which views; they also read or manipulate the information about the files in these buffers.
Views relate to the one or two editor windows inside Notepad++. Buffers are the individual file-editing buffers in each view. Because each view has a group of buffers, each buffer has an index within that view.
Don't get confused: while the editor objects are named editor1 and editor2, the views are numbered 0 and 1. That's why it's usually best to use %VIEW, either $VIEW{MAIN_VIEW} (0) or $VIEW{SUB_VIEW} (1), when selecting views.
$VIEW{MAIN_VIEW}
$VIEW{SUB_VIEW}
These methods allow you to change which file buffer is active in a given view, and get information about which view and buffer are active.
notepad->activateBufferID($bufferID);
Activates the given $bufferID
notepad->activateFile($filename);
Activates the buffer with the given $filename, regardless of view.
notepad->activateIndex($view, $index);
Activates the document with the given $view and $index.
The value for $view comes from %VIEW, either $VIEW{MAIN_VIEW} (0) or $VIEW{SUB_VIEW} (1).
$view
notepad->getCurrentBufferID();
Gets the bufferID of the currently active buffer
notepad->getCurrentDocIndex($view);
Gets the current active index for the given $view.
notepad->getCurrentView(); notepad->getCurrentScintilla();
Get the currently active view
The value returned comes from %VIEW, either $VIEW{MAIN_VIEW} (0) or $VIEW{SUB_VIEW} (1).
notepad->moveCurrentToOtherView();
Moves the active file from one view to another
notepad->cloneCurrentToOtherView();
Clones the active file from one view to the other, so it's now available in both views (which makes it easy to look at different sections of the same file)
These methods allow you to get the filename for a selected or active buffer, or get the list of all currently-open files.
notepad->getBufferFilename( $bufferid ); notepad->getBufferFilename( );
Gets the filename of the selected buffer.
If $bufferid is omitted, it will get the filename of the active document
notepad->getCurrentFilename();
Gets the filename of the active document
notepad->getFiles();
Gets a list of the open filenames.
Returns: A reference to an array-of-arrays, one row for each file, with filename, bufferID, index, and view as the elements of each row:
[ [$filename1, $bufferID1, $index1, $view1], ... [$filenameN, $bufferIDN, $indexN, $viewN] ]
notepad->getNumberOpenFiles($view); notepad->getNumberOpenFiles();
Returns the number of open files in $view, which should be 0 or 1. If $view is undef or not given or 0, return total number of files open in either view.
undef
It can use the %VIEW hash, either $VIEW{ALL_OPEN_FILES}, $VIEW{PRIMARY_VIEW}, or $VIEW{SECOND_VIEW}.
$VIEW{ALL_OPEN_FILES}
$VIEW{PRIMARY_VIEW}
$VIEW{SECOND_VIEW}
These methods allow you to determine or change the active language parser for the buffers.
notepad->getCurrentLang();
Get the current language type as an integer. See the %LANGTYPE hash.
To convert this integer into the name of the language, use "getLanguageName".
notepad->getLangType($bufferID); notepad->getLangType();
Gets the language type (integer) of the given $bufferID. If no $bufferID is given, then the language integer of the currently active buffer is returned.
See the %LANGTYPE hash for the language type integer.
if( notepad->getLangType() == $LANGTYPE{L_PERL} ) { $usingRightLanguage = 1; } # verify you're programming in the right language printf qq(%s => %s\n), $_, $LANGTYPE{$_} for sort { $LANGTYPE{$a} <=> $LANGTYPE{$b} } keys %LANGTYPE; # lists the mapping from key to integer, like L_PERL => 21
You can use the "getLanguageName" method to retrieve a string corresponding to the language integer.
notepad->setCurrentLang($langType);
Set the language type for the currently-active buffer. $langType should be from the %LANGTYPE hash.
$langType
notepad->setLangType($langType, $bufferID); notepad->setLangType($langType);
Sets the language type of the given bufferID. If not bufferID is given, sets the language for the currently active buffer.
$langType should be from the %LANGTYPE hash.
notepad->getLanguageName($langType); notepad->getLanguageDesc($langType);
Get the name and or longer description for the given language $langType, which should either be from the %LANGTYPE hash, or the return value from "getLangType" or "getCurrentLang".
Determines the encoding for a given file, and determines or changes the EOL-style for the file buffer.
notepad->getEncoding($bufferID); notepad->getEncoding();
Gets the encoding of the given bufferID, as an integer. If no bufferID is given, then the encoding of the currently active buffer is returned.
Returns: An integer corresponding to how the buffer is encoded.
Additional Info:
Using this integer as the key to the %Win32::Mechanize::NotepadPlusPlus::Notepad::Messages::BUFFERENCODING hash will give a string name corresponding to the encoding.
print $BUFFERENCODING{notepad->getEncoding()};
notepad->setEncoding($bufferID, $encoding); notepad->setEncoding($encoding);
Sets the encoding of the given bufferID. If no bufferID is given, then the encoding of the currently active buffer is set.
You can set $encoding as a value from the %Win32::Mechanize::NotepadPlusPlus::Notepad::Messages::BUFFERENCODING hash.
$encoding
notepad->setEncoding($BUFFERENCODING{UTF8_BOM});
Additional Info: This should behave similarly to using the "menuCommand" method, with the IDM_FORMAT_* values from %NPPIDM.
IDM_FORMAT_*
%NPPIDM
notepad->getFormatType($bufferID); notepad->getFormatType();
Gets the EOL format type (i.e. Windows [0], Unix [1] or old Mac EOL [2]) of the given bufferID. If no bufferID is given, then the format of the currently active buffer is returned.
Returns: The integers 0,1,or 2, corresponding to Windows EOL (CRLF), Unix/Linux (LF), or the old Mac EOL (CR).
notepad->setFormatType($formatType, $bufferID); notepad->setFormatType($formatType);
Sets the EOL format type (i.e. Windows [0], Unix [1] or old Mac EOL [2]) of the specified buffer ID. If not bufferID is passed, then the format type of the currently active buffer is set.
These methods allow you to reload the contents of the appropriate buffer from what is on disk.
notepad->reloadBuffer($bufferID);
Reloads the given $bufferID
notepad->reloadCurrentDocument();
Reloads the buffer of the current document
notepad->reloadFile($filename);
Reloads the buffer for the given $filename
When automating Notepad++, there are times when you may want an extra Scintilla Editor instance, even though it never needs to be seen inside the Notepad++ window. You can create and destroy hidden instances using these methods
notepad->createScintilla(); notepad->createScintilla( $parentHwnd );
Create a new Scintilla handle. Returns an Editor object. This Scintilla editor instance is not available to be displayed in either view, but in all other ways behaves like the main Scintilla Editor instances.
If $parentHwnd is passed (non-zero), that HWND will be used as the parent window for the new Scintilla; otherwise, Notepad++ itself will be used as the parent.
$parentHwnd
Please note: as of v7.8, there is no way to properly destroy the created Scintilla handle. There are a limited number of Scintilla handles that can be allocated before.
notepad->destroyScintilla($editor);
This method always returns a true, and warns that the method is deprecated.
In Notepad++ v7.7.1 and earlier, the NPPM_DESTROYSCINTILLAHANDLE tried to destroy the scintilla instance. However, this could crash Notepad++, so as of v7.8, Notepad++ ignores this message. To prevent Win32::Mechanize::NotepadPlusPlus from crashing Notepad++, the destroyScintilla() does not bother to send the message (in case it's Notepad++ v7.7.1 or earlier).
destroyScintilla()
notepad->hideMenu();
Hides the menu bar.
RETURN: The previous state: it will return 1 if it was hidden before, or 0 if it was shown before
notepad->showMenu();
Shows the menu bar
notepad->isMenuHidden();
Returns 1 if the menu bar is currently hidden, 0 if it is shown.
notepad->hideTabBar();
Hides the Tab bar.
notepad->showTabBar();
Shows the Tab bar
notepad->isTabBarHidden();
Returns 1 if the tab bar is currently hidden, 0 if it is shown.
notepad->hideToolBar();
Hides the toolbar.
notepad->showToolBar();
Shows the toolbar
notepad->isToolBarHidden();
Returns 1 if the toolbar is currently hidden, 0 if it is shown.
notepad->hideStatusBar();
Hides the status bar.
notepad->showStatusBar();
Shows the status bar
notepad->isStatusBarHidden();
Returns 1 if the status bar is currently hidden, 0 if it is shown.
notepad->setStatusBar($statusBarSection, $text);
Sets the selected status bar section to the given $text.
For $statusBarSection, use one of the %STATUSBAR values.
$statusBarSection
my $text = notepad->getStatusBar($statusBarSection);
Gets the text from the selected status bar section.
notepad->showDocList($toShowOrNot); # show the list if toShowOrNot is true my $shown = notepad->isDocListShown; # get the status
Sets or gets the status of whether the Document List panel is shown.
Note: Prior to Notepad++ v8.1.3, the Document List panel was previously known as the "Doc Switcher", which was often confused with the similarly-named MISC setting "Document Switcher (Ctrl+TAB)". Since these methods were added to this module after the panel was renamed in Notepad++, the module uses the new name, even if you use it with an older Notepad++.
notepad->docListDisableColumn($disableOrNot); # disables the extension column if disableOrNot is true
Sets whether or not the Document List panel disables (1) or shows (0) the extension in a separate column.
$mode = notepad->getLineNumberWidthMode(); notepad->setLineNumberWidthMode($mode);
Get or set the line number width mode, either dynamic width mode or constant width mode.
$mode uses one of the %LINENUMWIDTH values.
$mode
These were added in Notepad++ v7.9.2 to allow the line-numbering to be constant-width -- so the line number column will have the same width at line 1000000 as it shows at line 1000 -- or adjust to the width of the line number -- so the line-number column will be wider when you get to line 1000000 then when you were at line 1000. (Prior to v7.9.2, the line number width was always dynamic.)
notepad->getMainMenuHandle();
Gets the handle for the main Notepad++ application menu (which contains File, Edit, Search, ...).
notepad->getPluginMenuHandle();
Gets the handle for the Plugins menu.
notepad->menuCommand($menuCommand);
Runs a Notepad++ menu command. Use the MENUCOMMAND values from the %NPPIDM hash (described below), or integers directly from the nativeLang.xml file, or the string name from the hash.
notepad->runMenuCommand(@menuNames); notepad->runMenuCommand(@menuNames, { refreshCache => $value } );
Runs a command from the menus. For built-in menus use notepad->menuCommand(), for non built-in menus (e.g. TextFX and macros you’ve defined), use notepad->runMenuCommand(menuName, menuOption). For other plugin commands (in the plugin menu), use notepad->runPluginCommand(pluginName, menuOption).
notepad->menuCommand()
notepad->runMenuCommand(menuName, menuOption)
notepad->runPluginCommand(pluginName, menuOption)
Menus are searched for the text, and when found, the internal ID of the menu command is cached. When runMenuCommand is called, the cache is first checked if it holds the internal ID for the given menuName and menuOption. If it does, it simply uses the value from the cache. If the ID could have been updated (for example, you’re calling the name of macro that has been removed and added again), set refreshCache to any Perl expression that evaluates as True.
@menuNames is a one-or-more element list of strings; each string can either be a name from the menu hierarchy (either a menu name or a command name) or a pipe-separated string with multiple names. See the example below.
@menuNames
Returns: True if the menu command was found, otherwise False
e.g.:
notepad()->runMenuCommand('Tools', 'SHA-256', 'Generate from selection into clipboard'); notepad()->runMenuCommand('Tools', 'SHA-256 | Generate from selection into clipboard'); notepad()->runMenuCommand('Tools | SHA-256', 'Generate from selection into clipboard'); notepad()->runMenuCommand('Tools | SHA-256 | Generate from selection into clipboard'); notepad()->runMenuCommand('Macro', 'Trim Trailing Space and Save', { refreshCache => 1 });
notepad->runPluginCommand($pluginName, $menuOption, $refreshCache); notepad->runPluginCommand($pluginName, $menuOption);
Runs a command from the plugin menu. Use to run direct commands from the Plugins menu. To call TextFX or other menu functions, either use notepad->menuCommand(menuCommand) (for Notepad++ menu commands), or notepad->runMenuCommand(menuName, menuOption) for TextFX or non standard menus (such as macro names).
notepad->menuCommand(menuCommand)
Note that menuOption can be a submenu in a plugin’s menu. So:
notepad->runPluginCommand('Python Script', 'demo script');
Could run a script called “demo script” from the Scripts submenu of Python Script.
Menus are searched for the text, and when found, the internal ID of the menu command is cached. When runPluginCommand is called, the cache is first checked if it holds the internal ID for the given menuName and menuOption. If it does, it simply uses the value from the cache. If the ID could have been updated (for example, you’re calling the name of macro that has been removed and added again), set refreshCache to True. This is False by default.
notepad->runPluginCommand(‘XML Tools’, ‘Pretty Print (XML only)’);
notepad->getShortcutByCmdId(22000); # returns the shortcut info for the plugin command with ID=22000
Gets the mapped command shortcut for a plugin-menu command. (Does not work on the other menus.) May be called after getting NPPN_READY notification.
Returns: Shortcut information as a list (array), where the first three elements are Booleans indicating the state of the the Ctrl and Alt and Shift keys, and the fourth element is the shortcut key.
notepad->removeShortcutByCmdId(22000); # clears the shortcut info for the plugin command with ID=22000
Clears the mapped command shortcut for a plugin-menu command. (Does not work on the other menus.) May be called after getting NPPN_READY notification.
Returns:
notepad->messageBox($message, $title, $flags); notepad->messageBox($message, $title); notepad->messageBox($message);
Displays a message box with the given message and title.
Flags can be 0 for a standard ‘OK’ message box, or a combination of values from the %WINMSGBOX hash.
Returns: The value from one of the %WINMSGBOX RESULT_* entries.
RESULT_*
Example:
my $mb = notepad->messageBox('message', 'title', $WINMSGBOX{OKCANCEL}); if( $mb == $WINMSGBOX{RETURN_OK} ) { ... } else { ... }
notepad->prompt($prompt, $title, $defaultText); notepad->prompt($prompt, $title);
Prompts the user for some text. Optionally provide the default text to initialise the entry field.
Returns: The string entered.
None if cancel was pressed (note that is different to an empty string, which means that no input was given)
notepad->SendMessage( $msgid, $wparam, $lparam );
For any messages not implemented in the API, if you know the appropriate $msgid, and what are needed as $wparam and $lparam, you can send the message to the Notepad GUI directly.
If you have developed a wrapper for a missing message, feel free to send in a Pull Request, or open an issue, including your wrapper code.
These give details about the current instance of Notepad++, or the Perl Library, or Perl itself.
notepad->getNppVersion();
Gets the Notepad++ version as a string.
(This was called getVersion in the PythonScript API.)
notepad->getPluginVersion();
Gets the PythonScript plugin version as a string.
notepad->getPerlVersion();
Gets the Perl interpreter version as a string.
notepad->getPerlBits();
Gets the Perl interpreter bits-information (32-bit vs 64-bit) as an integer.
notepad->getCommandLine();
Gets the command line used to start Notepad++, when using v8.0 or newer. On older versions, returns undef.
notepad->getNppDir();
Gets the directory Notepad++ is running in (i.e. the location of notepad++.exe)
notepad->getPluginConfigDir();
Gets the plugin config directory.
notepad->getNppVar($userVar);
Gets the value of the specified Notepad++ User Variable
Use $userVar from %INTERNALVAR.
$settings_folder = notepad->getSettingsOnCloudPath();
Get the "Settings on Cloud" path (from Settings > Preferences > Cloud). It is useful if plugins want to store its settings on Cloud, if this path is set.
my $debugInfoHashRef = notepad->getDebugInfo(); my $isAdmin = notepad->getDebugInfo('Admin mode'); my @vals = notepad->getDebugInfo(@keys);
Parses the contents of the ?-menu's Debug Info dialog box and gives you read-only access to an anonymous hash or individual values from the information. If the requested key(s) do not exist, it will return undef. The keys are the lowercase versions of the strings before the colons in each line of the Debug Info. Not all keys are available in all instances or versions of Notepad++.
KEY | Description ------------------------+--------------- '-APP' | Notepad++ version number (first line from Debug Info) 'build time' | The date and time that this version of Notepad++ was built 'path' | The path to the notepad++.exe executable 'command line' | Command line arguments for this instance of Notepad++ (v8.x) 'admin mode' | Whether Adminstrator Mode is "ON" or "OFF" 'local conf mode' | Whether config files will be found in the notepad++ folder or not ("ON" or "OFF") 'cloud config' | Indicates if config files are in the cloud folder (lists folder) or not ("OFF") (v8.x) 'os name' | Name of the Windows OS used 'os version' | Version of the Windows OS used 'os build' | Build of the Windows OS used 'current ansi codepage' | Codepage number active for "ANSI" files 'plugins' | Space-separated list of plugin DLLs loaded
Callbacks are functions that are registered to various events.
FUTURE: they were in the PythonScript plugin, but I don't know if they'll be able to work in the remote perl module. If I ever integrated more tightly with a Notepad++ plugin, it may be that they can be implemented then.
The primary interface is through the "NOTEPAD OBJECT API", implemented through object methods.
However, there are some hash variables that are useful for use with the API. These can be exported individually, or using the :vars or :all tags.
:vars
:all
Exports just the variables in Win32::Mechanize::NotepadPlusPlus::Notepad::Messages.
It's usually used via Win32::Mechanize::NotepadPlusPlus's :vars tag, which exports the variables in Win32::Mechanize::NotepadPlusPlus::Notepad::Messages and in Win32::Mechanize::NotepadPlusPlus::Editor::Messages:
use Win32::Mechanize::NotepadPlusPlus ':vars';
The full documentation for the available variables is in Win32::Mechanize::NotepadPlusPlus::Notepad::Messages. Additionally, some of frequently-used hashes are summarized below.
This hash contains maps all known message names from Notepad_plus_msgs.h, which are useful for passing to the SendMessage method.
SendMessage
You can find out the names and values of all the messages using:
use Win32::Mechanize::NotepadPlusPlus ':vars'; printf "%-40s => %s\n", $_, $NPPMSG{$_} for sort keys %NPPMSG;
This hash contains maps all known message names from menuCmdID.h, which are useful for passing to the "notepad()->menuCommand()" method (or the SendMessage method with the NPPM_MENUCOMMAND message.)
use Win32::Mechanize::NotepadPlusPlus ':vars'; printf "%-40s => %s\n", $_, $NPPIDM{$_} for sort keys %NPPIDM;
... or by looking at the source code for Win32::Mechanize::NotepadPlusPlus::Notepad::Messages.
The numerical values from this hash can be passed to notepad->setEncoding to change the encoding of the buffer; the numerical values returned from notepad->getEncoding can be passed as keys for this hash to convert the encoding number back to a string.
See the full table of values at %Win32::Mechanize::NotepadPlusPlus::Notepad::Messages::BUFFERENCODING
Exports everything that can be exported.
Installed as part of Win32::Mechanize::NotepadPlusPlus
Peter C. Jones <petercj AT cpan DOT org>
<petercj AT cpan DOT org>
Please report any bugs or feature requests emailing <bug-Win32-Mechanize-NotepadPlusPlus AT rt.cpan.org> or thru the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Win32-Mechanize-NotepadPlusPlus, or thru the repository's interface at https://github.com/pryrt/Win32-Mechanize-NotepadPlusPlus/issues.
<bug-Win32-Mechanize-NotepadPlusPlus AT rt.cpan.org>
Copyright (C) 2019,2020,2021 Peter C. Jones
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information.
To install Win32::Mechanize::NotepadPlusPlus, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Win32::Mechanize::NotepadPlusPlus
CPAN shell
perl -MCPAN -e shell install Win32::Mechanize::NotepadPlusPlus
For more information on module installation, please visit the detailed CPAN module installation guide.