| View previous topic :: View next topic |
| Author |
Message |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Thu Jun 28, 2007 11:45 am Post subject: Scripts collection |
|
|
Ув. пользователи AkelPad'а!
Предлагаю в этой теме делиться своими наработками (скриптами)!
Этим мы поможем и друг другу и более широкому и быстрому распространению этой замечательной проги!
P.S. Имеющиеся скрипты сгруппированные по авторам.
Dear users AkelPad'а!
I suggest to share in this theme the operating time (scripts)!
We will help these and each other both to wider and fast expansion of this remarkable program!
P.S. Available scripts are grouped by authors.
VladSh
VladSh.zip - scripts archive.
- ParagraphCreate.js - Formation paragraph by previous line indented
- SumNumbers.js - The sum of all the numbers contained in the selected text
- FullScreenEx.js - go to FullScreen-mode with additional options for display panels; a return to normal-mode
- FileTabs.js - script "library" for working with AkelPad tabs
- SpellCheckAddToWhiteList.js - add the current word to the white list; (script alternative with WriteInWhiteSpellCheckList.vbs)
- SpellCheckUnderlightSwitcher.js - enable/Disable highlighting misspelled words
- CodeFoldSwitcher.js - show area/window code navigation
- SpecialCharSwitcher.js - displaying group of special characters
- ScriptNameCopyAsBBCode.js - copies the name of the script in BBCode, substituting in URL is first found the link in edit window
- ScriptCopyToBlock.js - copies the contents of the file to 'more'-structure ... for put on a forum
- CutFormattingText.js - cutting text with formatting
- DownloadMaster.js - downloading a file by URL using Download Master
- OpenSessionsDir.js - Opens the directory where the files are stored sessions
- TranslateWithGoogleAPI.js - translates selected text using the Google API
- CaseUpperLower.js, CaseUpperLowerProper.js - change case in a loop
- BlockDeclose.js - declose scriptblock
- BlockSelect.js - select textblock by borders
- reassoc.js - associating with program the file extensions, listed in AkelPad.ini
- Settings.js - script "library" for working with settings
- INI.js - "library" for working with ini-files
- Favourites.js - Export/Replace Favourites-menu
- XMLGetAttrValues.js - receiving appointed attributes of each line of XML-file
- SmartBackspace.js - deleting block of whitespaces; for other characters - a usual deleting (1 symbol)
- ParagraphRemove.js - remove the entire paragraph by Ctrl+Alt+Y
- RegJump.js - opens the selected branch in the registry editor
- ExecuteScriptMenu.js - run the script from his own menu of some scripts
- OpenAllFilesFromFileFolder.js - opens all files located in specified folder
- ProcessFolderFiles.js - a script template for working with all files located in specified folder
- ProcessRowText.js - a script template for working with all rows to the text (script alternative with ProcessSelectedText.js)
- ShiftVerticaly.js - move the text vertically (script alternative with MoveLinesUpDown.js)
- OpenHelpString.js - opens a file on the specified path, opens it and is positioned at a certain text
- OpenScriptsHelp.js - opens help for Scripts-plugin and goes to the requested method
- OpenCoderParamsFile.js - opens coder-plugin configuration file
- ShowMenuEx.js - getting the value selected in the user menu (menu autogenerated from parameter files)
- ScriptNamesToContextMenuStrings.js - converting the scriptnames to the string for ContextMenu-plugin
- LSConst.js - LS: convert column names items in line descriptions of the constants
- LSGetItemValue.js - LS: convert dot-syntax GetItemValue to the standard
- LSReplaceItemValue.js - LS: convert dot-syntax ReplaceItemValue to the standard
- LSFunctionsItemToConst.js - LS: The transformation field names in the functions to the constants
- CaretSelect.js - select the word or link at the cursor position
- WordCaretCopy.js - copy the word at the cursor position
- SpacesToTabs.js - convert space to tabulation
- InternetRequest.js - internet request for formed url in the arguments
- SaveAs.js - "Save as ..." by analogy with the way it makes MS Word
- OpenByLSC.js - open by Linked, Selected or Clipboard text: file (supported the opening of scripts from AkalPad directory), folder; url, ets...
- DelInsideSpaces.js - delete repeated spaces inside the text
- CreateSubParagraph.js - creating a new line with indented and existing type of item
- RecalcLineNumbers.js - recalculation of line numbers
- CreateLNMemo.js - create letter in the Lotus Notes client on the basis of an open file
- urlOpen.js - open url or site
- UndoAllNoScroll.js - undo all changes without scroll
- DelEmptyLines.js - delete lines feed (alternative script)
- DelLeadTrailSpaces.js - delete leading and trailing spaces selected or all text (alternative script)
- DelLineFeed.js - delete lines feed
- HTMLDelUselessTags.js - remove unnecessary (heavier page) HTML tags
- HTMLDelAllTags.js - remove all HTML tags
- DeleteFile.js - delete current opened file
- InsertBefore.js - insert any values before each line
- HTMLlinefeed.js - insert line feed after <br />, replace <br> on <br /> (XHTML)
- CommentsAdd.js - commented text or block of text
- CommentsDel.js - decommented text or block of text
- CtrlDown.js - formation, carrying over and disclosing of symbols of the block
- selCompleteLine.js - common functions for work with the text
- OpenEx.js - opening a file dialog with a choice of extensions from the list
- RenameFileDialog.js - rename current editing file with dialog
- CommonFunctions.js - common functions for WinFS
- NewFilebyRecent.js - creation of a new file on the basis of the contained allocated file in the list of the fresh
- insertStructure.js - Convert selected lines to predefine structure
- CorrectCBCodepage.js - correction of Cyrillic characters of Clipboard
- TagLinking.js - universal linking selectedText
- FileNameCopyToCB.js - copy to clipboard file name short
- FilePathCopyToCB.js - copy to clipboard file name full or file directory
- InsertFileEx.js - Inserts the selected text file into the current file
- SpellCheckMSWord.js - spell check using Microsoft Word (alternative script)
- TestCurrentScript.js - running open in current tab script (for testing)
- ConsoleRun.js - executes the command by WshShell.Run, that is, through cmd, but without displaying the DOS-window, the result of execution issued from the console in the current file
- ConsoleExec.js - executes the command by WshShell.Exec; used to run some applications, the analog command "Start" -> "Run "
- DateFormat.js - function return time and date in specified format
- DateInsert.js - insert DateTime in specified format
- DateCopyToCB.js - copy to clipboard DateTime in specified format
KDJ
KDJ.zip - scripts archive.
- TabMinMax.js - Minimize, maximize or restore tab in MDI mode.
- FindReplaceEx.js, FindReplaceEx_part2.js - Extended version of "Find/Replace" dialog.
- GoToEx.js - "Go to" dialog with argument
- ScreenView.js - Switch between different views of AkelPad screen.
- FindFiles.js - Search files by name and content
- FontCycleSwitch.js, FontCycleSwitch_PerverseCode.js - Cycle switch between fonts.
- InputBox_function.js, InputBox_example.js - InputBox with multiple edit value and variable window width.
- PluginText.js - Operations on the text from plugins: Coder, ContextMenu, Hotkeys and ToolBar.
- FileAndStream.js, FileAndStream_part2.js, FileAndStream_part3.js, FileAndStream_part4.js - Manager of files and NTFS streams.
- SendData.js - Sends data and keystrokes from text file or Excel worksheet to another window.
- CaretOptionsSwitch.js - Switching four caret options.
- FileStreamsList.js, FileStreamCreate.js, FileStreamDelete.js, FileStreamOpen.js, FileStreamRead.js, FileStreamWrite.js - Examples of use FileStreams_functions.js
- FileStreams_functions.js - Features to support NTFS file streams (alternate data streams).
- WindowsList.js - Windows lister.
- EnumerateWindows_functions.js - Enumerates top level windows and child windows (functions).
- FontDialogMonospace.js, ChooseFont_examples.js - Examples of use ChooseFont function.
- ChooseFont_function.js - Displays a dialog box with a choice of fonts.
- FontIniRestore.js, FontIniRestore.vbs - Restores initial settings of font face, style and size from AkelPad.ini or registry.
- PlugTextReadFromIni.js - Opens text of ContextMenu/ToolBar plugin in AkelPad edit window.
- PlugTextToAkelPad.js - Copy the text from edit window of ContextMenu/ToolBar plugin to AkelPad or vice versa.
- PlugToolBarAkelFont.js - Run ContextMenu plugin with font, that is set in AkelPad or modified.
- PlugContextMenuAkelFont.js - Change the font in ToolBar plugin window.
- MarginsChange.js - Change margins in edit window.
- ShowScrollBar.js - Show/hide scroll bars in edit window.
- MapNetDrive.js - Mapping network drives.
- InsertFolderName.js, InsertFolderName_alternative.js, BrowseForFolder_function.js - inserts folder name using SHBrowseForFolder function.
- Translator.js - translates text via Google and MS Bing.
- InsertDateFromCalendar.js - inserts date and/or time from calendar.
- ResetUrlDelimiters.js - restores default value URL delimiters (Options->Settings->Editor 2->Delimiters)
- ResetUrlPrefixes.js - restores default value URL prefixes (Options->Settings->Editor 2->Prefixes)
- InsertTabOrSpaces.js - inserts a tabulation or spaces, inversely to setting Options->Settings->Editor 1->Tab size->Spaces (bTabStopAsSpaces)
- ReplaceReplicateCharsWithOne.js - replace replicate chars with one char
- SortWords.js - sort words.
- RegExpTestJS.js: part 1, part 2 - regular expression tester for JavaScript
- SortList.js - sorts lists in lines by using Format plugin
- SortLines.js - sorts lines according to two keys: by line length and by string, alphabetically or numerically; removes duplicate lines, reverses the order of lines
- SortInColumns.js
- GetTextRangeColumn_example.js - this function retrieves columnar text, without selecting
- DateToShortLocaleString_example.js - this function returns a short local date from system date
- ArrayTextSort_example.js - one-dimensional text array sorting function
- Array2DSort_example.js - one or two-dimensional array sorting function
- Array2DTransp_example.js - two-dimensional array transposition function
- BracketsGoTo.js - go to or select between nearest brackets
- FileInfo.js - file info and text statistics
- LineMaxLength.js - information about maximum line length
- SelectRangeText.js - select range of text, change selection
- FontIniSize.js, FontIniSize.vbs - Set initial font size from AkelPad.ini or registry
- ColumnsSum.js - sum numbers (expressions) in selected column
- ColumnsReplace.js - replace text in selected column
- ColumnsDuplicateSelect.js - select entire columns or duplicate selected columns
- SelectionOpenInTab.js - open selected text in new tab
- SelectionSwitchCaretMove.js - switch selection mode (column on/off), move caret in the selection
- SelectionSwitch.js - changing selection mode (column on/off) - simple version
- AlignJustify.js - align selected lines to the left, right, center or justify
- SelectBeforeAfterCaret.js - select all text before or after the caret
- CSVToColumnText.js - converts text in csv format to text in columns
- CalculatorJS.js - JS expression calculator
- InsertTextLN.js - insert text and line number at the beginning and at the end of selection
- InsertText.js - insert text at the beginning and at the end of selection
- InsertFileNamePath.js - inserts to the text file name or path and copy to the clipboard
- WordsMoveSelect.js - move left/right selected words or only select whole words
- TextMove.js - moves selected text to the left and right or up and down
- SplitSwitch_alternative.js - split window switch (alternative script)
- LinesSelectCopyMoveDuplicate.js, MoveLinesUpDown_alt.js, LinesMoveDuplicateSelect.js - Selects entire lines, copies, moves up/down or duplicates selected lines.
Infocatcher
Instructor
FeyFre
- QuoteExtend.js - Extends(or creates) selection bounding on quotes or parenthesis.
- History.js - Resident script, which allows to restore recently closed documents.
- XMLValidator.js - Validates selected XML fragment or entire text.
- coder2wl.js - Merges list of words defined in Coder's syntax files with SpellCheck's whitelists.
- SetMargins.js - Sets both left and right margins.
- ADODB.js - Microsoft Data Access - ActiveX Data Objects - constants and helpers set
- SetCoderExt.js - set Coder Extension theme by extension
- transparency.js - make AkelPad semitransparent
- Win32 Constants Library - set of constants usable during writing scripts using Win32 system calls
- AutoTag.js - autoclosing tag style for BBCode and XML/HTML/SGML
- ChooseColor.js - choose & insert/change color in RGB-format by standard color selection dialog
- zen-coding - zen-coding bindings for AkelPad
Andrey_A_A
se7h
Visitor7
DV
- KeySubst.js - Script replaces keystrokes
- RunMe.js - My vision of running a file from within AkelPad (including compiling)
- ProcessSelectedText.js - a script template for modifying the text selected in AkelPad
Yustas.NeO
Fr0sT
- OpenAsEmail.js - Open raw email file in associated mailer ("eml" extension must be registered in OS)
- Log.js - output message to log file snippet
- base64.js - converts selection to Base64 and vice versa
opk44
cnnnc
oyaebu
Idjo
lexa
bluestone
levilevi
- createFile.js - create a new text file in current editing file directory
wisgest
- Evaluate.js - simple mathematical (JavaScript) Calculator
F. Phoenix
akkorn
Ссылка на некоторые архивы-сборники скриптов: http://akelpad.sourceforge.net/files/plugs/Scripts/
Last edited by VladSh on Tue Dec 25, 2012 10:15 am; edited 58 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Thu Jun 28, 2007 11:50 am Post subject: |
|
|
InsertDate.js Instructor'а, преобразовал в функцию, возвращающую дату в опред. формате:
DateFormat.js
| Code: | ///Script "library" for working with time and date; return it in specified format. Must be placed in ...\Scripts\Include\
///Скрипт-"библиотека" для работы с датами; возвращает дату/время в определённом формате. Должен находиться в директории ...\Scripts\Include\
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1211#1211
// Version: 2.1 (2011.07.20)
//
// Time:
// h Hours with no leading zero for single-digit hours; 12-hour clock.
// hh Hours with leading zero for single-digit hours; 12-hour clock.
// H Hours with no leading zero for single-digit hours; 24-hour clock.
// HH Hours with leading zero for single-digit hours; 24-hour clock.
// m Minutes with no leading zero for single-digit minutes.
// mm Minutes with leading zero for single-digit minutes.
// s Seconds with no leading zero for single-digit seconds.
// ss Seconds with leading zero for single-digit seconds.
// t One character time-marker string, such as A or P.
// tt Multicharacter time-marker string, such as AM or PM.
//
// Date:
// d Day of month as digits with no leading zero for single-digit days.
// dd Day of month as digits with leading zero for single-digit days.
// ddd Day of week as a three-letter abbreviation.
// dddd Day of week as its full name.
// M Month as digits with no leading zero for single-digit months.
// MM Month as digits with leading zero for single-digit months.
// MMM Month as a three-letter abbreviation.
// MMMM Month as its full name.
// y Year as last two digits, but with no leading zero for years less than 10.
// yy Year as last two digits, but with leading zero for years less than 10.
// yyyy Year represented by full four digits.
//
// Example:
// "H:mm:ss dd MMMM yyyy" -> "12:50:24 07 January 2008"
function DateFormat(pFormat)
{
if (AkelPad.GetMainWnd())
{
if (!pFormat)
pFormat = AkelPad.GetArgLine() || "dd.MM.yyyy HH:mm"; //default value
return TimeFormat(pFormat);
}
}
function TimeFormat(pFormat)
{
var _TCHAR;
var _TSTR;
var _TSIZE;
if (AkelPad.IsOldWindows())
{
_TCHAR = "A";
_TSTR = 0 /*DT_ANSI*/;
_TSIZE = 1 /*sizeof(char)*/;
}
else
{
_TCHAR = "W";
_TSTR = 1 /*DT_UNICODE*/;
_TSIZE = 2 /*sizeof(wchar_t)*/;
}
var lpFormatBuffer;
var lpTimeBuffer;
var pTime = "";
if (lpFormatBuffer = AkelPad.MemAlloc(256 * _TSIZE))
{
AkelPad.MemCopy(lpFormatBuffer, pFormat.substr(0, 255), _TSTR);
if (lpTimeBuffer = AkelPad.MemAlloc(256 * _TSIZE))
{
var oFunction = AkelPad.SystemFunction();
oFunction.AddParameter(1024); //LOCALE_USER_DEFAULT
oFunction.AddParameter(0);
oFunction.AddParameter(0);
oFunction.AddParameter(lpFormatBuffer);
oFunction.AddParameter(lpTimeBuffer);
oFunction.AddParameter(256);
oFunction.Call("kernel32::GetTimeFormat" + _TCHAR);
oFunction.AddParameter(1024); //LOCALE_USER_DEFAULT
oFunction.AddParameter(0);
oFunction.AddParameter(0);
oFunction.AddParameter(lpTimeBuffer);
oFunction.AddParameter(lpFormatBuffer);
oFunction.AddParameter(256);
oFunction.Call("kernel32::GetDateFormat" + _TCHAR);
pTime = AkelPad.MemRead(lpFormatBuffer, _TSTR);
AkelPad.MemFree(lpTimeBuffer);
}
AkelPad.MemFree(lpFormatBuffer);
}
return pTime;
}
|
Примеры использования:
- вставка в окно редактирования: DateInsert.js
| Code: | ///Insert DateTime in specified format
///Вставка даты-времени в определённом в аргументах формате
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1213#1213
// Version: 1.3 (2011.07.20)
if (! AkelPad.Include("DateFormat.js")) WScript.Quit();
AkelPad.ReplaceSel(DateFormat("")); |
Внешние вызовы из ContextMenu:
| Code: | "Insert"
{
;...
-"Date" Call("Scripts::Main", 1, "DateInsert.js", `"dd.MM.yyyy"`, 0)
-"Date Turn" Call("Scripts::Main", 1, "DateInsert.js", `"yyyy.MM.dd"`, 0)
-"Date-Time Turn" Call("Scripts::Main", 1, "DateInsert.js", `"yyyy.MM.dd HH:mm:ss"`, 0)
} |
- копирование в буфер обмена: DateCopyToCB.js
| Code: | ///Copy to clipboard DateTime in specified format
///Копирование в буфер обмена даты-времени в определённом в аргументах формате
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1346#1346
// Version: 1.3 (2011.07.20)
if (! AkelPad.Include("DateFormat.js")) WScript.Quit();
AkelPad.SetClipboardText(DateFormat("")); |
Внешние вызовы из ContextMenu:
| Code: | "Copy to Clipboard"
{
;...
-"Date" Call("Scripts::Main", 1, "DateCopyToCB.js", `""`)
-"Date Turn" Call("Scripts::Main", 1, "DateCopyToCB.js", `"yyyyMMdd"`)
-"Date Turn (.)" Call("Scripts::Main", 1, "DateCopyToCB.js", `"yyyy.MM.dd"`)
-"Date Turn Full" Call("Scripts::Main", 1, "DateCopyToCB.js", `"yyyyMMdd_HHmmss"`)
} |
Last edited by VladSh on Wed Jul 20, 2011 6:14 pm; edited 17 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Thu Jun 28, 2007 11:55 am Post subject: вызов для каждого языка своего компилятора |
|
|
ConsoleExec.js
| Code: | ///Выполняет команду методом WshShell.Exec; используется для запуска некоторых приложений, аналог команды "Пуск" -> "Выполнить"
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1212#1212
// Version: 2.11 (2012.12.18)
//
// Параметры:
// cmd - имя команды; если указано, то меню выводиться не будет, а выполнится указанная команда;
// sep - разделитель для разбора идентификаторов и надписей в param-файле (подробнее см. параметр pParsepProcSep в ShowMenuEx.js)
//
// Примеры:
// -"Калькулятор" Call("Scripts::Main", 1, "ConsoleExec.js", `-cmd="calc"`)
// -"Выбор программы для запуска..." Call("Scripts::Main", 1, "ConsoleExec.js", `-sep="=" -ignore1menu=1`) - пример задания игнорирования вывода меню, если в param-файле одна запись
var pCommand = AkelPad.GetArgValue("cmd", "");
if (!pCommand) {
if (! AkelPad.Include("ShowMenuEx.js")) WScript.Quit();
pCommand = getSelectedMenuItem(POS_CURSOR, AkelPad.GetArgValue("sep", ""), 0);
if (!pCommand) WScript.Quit();
}
var WshShell = new ActiveXObject("WScript.Shell");
try {
WshShell.Exec(pCommand);
}
catch (e) {
var errInfo = e.name + ": " + e.description + "Command: " + pCommand;
if (AkelPad.Call("Log::Output",5, errInfo, -1,1) == -1)
AkelPad.MessageBox(AkelPad.GetEditWnd(), errInfo, WScript.ScriptName, 48 /*MB_EXCLAMATION*/);
} | Идея взята отсюда (Exec.js).
Пример файла параметров ConsoleExec.param:
| Code: | notepad = Блокнот
regedit = Regedit
calc = Калькулятор
%SystemRoot%\system32\restore\rstrui.exe = Восстановление системы |
ConsoleRun.js
| Code: | ///Выполняет команду с помощью cmd (аналог WshShell.Run), с выводом результата выполнения в консоли Log-плагина
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1212#1212
// Version: 2.8 (2012.12.18)
//
// -"ipconfig" Call("Scripts::Main", 1, "ConsoleRun.js", `-cmd="ipconfig"`)
var pCommand = AkelPad.GetArgValue("cmd", "");
if (!pCommand) {
if (! AkelPad.Include("ShowMenuEx.js")) WScript.Quit();
pCommand = getSelectedMenuItem(POS_CURSOR, "", 0);
if (!pCommand) WScript.Quit();
}
AkelPad.Call("Log::Output", 1, pCommand, "", "", "", -1, -1); | Это переделанный скрипт Instructor'а ExecConsole.js.
Пример файла параметров ConsoleRun.param:
Скрипты используют ShowMenuEx.js.
Last edited by VladSh on Tue Dec 18, 2012 2:09 pm; edited 22 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Thu Jun 28, 2007 12:02 pm Post subject: Скрипт для вставки даты |
|
|
TestCurrentScript.js
| Code: | ///Running open in current tab script (for testing)
///Запуск открытого в текущей вкладке скрипта
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1213#1213
// Version: 1.1 (2011.02.02)
// Предлагаемая комбинация клавиш: Alt+T
var fso = new ActiveXObject("Scripting.FileSystemObject");
var pFileName = fso.GetFileName(AkelPad.GetEditFile(0));
if (pFileName) AkelPad.Call("Scripts::Main", 1, pFileName); |
NB: Instructor thanks!
Last edited by VladSh on Thu Jul 21, 2011 10:34 am; edited 17 times in total |
|
| Back to top |
|
 |
wisgest
Joined: 24 Jun 2007 Posts: 63 Location: Belorussia
|
Posted: Sun Jul 15, 2007 11:17 am Post subject: Evaluate.js |
|
|
Типа встроенный калькулятор. Выделяем какое-нибудь выражение, например, "13.34678+36777.89/8", вызываем скрипт, получаем результат "4610.58303" (кстати, я его таким образом и получил), если результат нравится, нажимаем "OK" - результат в буфере обмена (не нравится - "Отмена"), теперь можем, например, заменить им первоначальное выражение.
Evaluate.js
| Code: | // Применяет к выделенному тексту JavaScript-функцию eval(),
// сообщает вычисленное значение и при подтверждении пользователя
// запоминает его в буфере обмена.
// (Математические функции и константы доступны без префикса "Math.";
// при сложных вычислениях, использующих операторы JavaScript,
// можно использовать функцию Trace(<значение>[, <подсказка>]),
// возвращающую и показывающую промежуточное значение <значение>,
// которое тоже можно запоминать в буфере обмена.)
var
AkelPad = new ActiveXObject("AkelPad.document"),
WshShell = new ActiveXObject("WScript.Shell"),
Err;
var
Title = WScript.ScriptName,
SelText = AkelPad.getSelText();
if (SelText == "") {
WshShell.Popup("Отсутствует выделенный текст.", 0, Title, 0 + 48);
WScript.Quit();
}
try {
with (Math) Trace(eval(SelText), "Вычисленное значение");
} catch(Err) {
WshShell.Popup(Err.description, 0, Title, 0 + 16);
}
function Trace(Value, Prompt) {
Prompt = (Prompt? (Prompt + ":\n\n"): "") + Value;
if (WshShell.Popup(Prompt, 0, Title, 1 + 64) == 1)
AkelPad.SetClipboardText(Value);
return Value;
}
|
Примеры использования:
56 * 13 - результат 728;
sin(PI/2) - синус пи на два (результат 1);
res=0; for (i=1; i<=500; i++) res=res+i*i - сумма квадратов первых пятиста целых чисел (41791750);
x=34+56; Trace(x,"Промежуточное значение"); x+26 - сумма трех чисел (34, 56 и 26) с выводом промежуточного результата;
Trace(34+56)+26 - предыдущий пример в другой записи. |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Mon Jul 16, 2007 3:40 pm Post subject: Копирование даты в буфер обмена |
|
|
SpellCheckMSWord.js
| Code: | ///Spell check using Microsoft Word
///Проверка орфографии используя MS Word
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1346#1346
// Version: 1.2 (2011.06.08)
var pSelText;
var hMainWnd = AkelPad.GetMainWnd();
var nCursor = -1;
if (hMainWnd)
{
var pScriptName = WScript.ScriptName;
pSelText = AkelPad.GetSelText();
if (!pSelText)
{
nCursor = AkelPad.GetSelStart();
pSelText = AkelPad.GetTextRange(0, -1);
}
if (pSelText.charCodeAt(0) != 0)
{
var Word = new ActiveXObject("Word.application");
if (Word)
{
var oSpellDoc;
var pMessage;
var pTextIn;
var pTextOut;
Word.Visible = false;
Word.Options.SuggestSpellingCorrections = true;
if (oSpellDoc = Word.Documents.Add())
{
Word.ActiveWindow.WindowState = 2; //wdWindowStateMinimize
oSpellDoc.Content.Text = pSelText;
pTextIn = oSpellDoc.Content.Text;
if (Word.Options.CheckGrammarWithSpelling == true)
oSpellDoc.CheckGrammar();
else
oSpellDoc.CheckSpelling();
pTextOut = oSpellDoc.Content.Text;
oSpellDoc.Close(false);
if (pTextIn != pTextOut)
{
if (AkelPad.MessageBox(hMainWnd, GetLangString(3), pScriptName, 36 /*MB_ICONQUESTION|MB_YESNO*/) == 6 /*IDYES*/)
{
if (nCursor != -1) AkelPad.SetSel(0, -1);
AkelPad.ReplaceSel(pTextOut.substr(0, pTextOut.length - 1));
}
}
}
Word.Quit(0);
}
else
{
AkelPad.MessageBox(hMainWnd, GetLangString(0), pScriptName, 48 /*MB_ICONEXCLAMATION*/);
}
}
else
{
AkelPad.MessageBox(hMainWnd, GetLangString(1), pScriptName, 64 /*MB_ICONINFORMATION*/);
}
}
if (nCursor != -1) AkelPad.SetSel(nCursor, nCursor);
function GetLangString(nStringID)
{
var nLangID = AkelPad.GetLangId(1 /*LANGID_PRIMARY*/);
if (nLangID == 0x19) //LANG_RUSSIAN
{
if (nStringID == 0)
return "Необходимо сначала установить Microsoft Word 97 или выше.";
if (nStringID == 1)
return "Текст отсутствует.";
if (nStringID == 3)
return "Вставить исправленый текст?";
}
else
{
if (nStringID == 0)
return "You must first install Microsoft Word 97 or higher.";
if (nStringID == 1)
return "The text is absent.";
if (nStringID == 3)
return "Insert corrected text?";
}
return "";
} |
Данный скрипт является модификацией скрипта SpellCheck.js из дистрибутива Scripts-плагина.
Last edited by VladSh on Wed Jul 20, 2011 6:17 pm; edited 13 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Wed Jul 18, 2007 10:15 am Post subject: СКРИПТ ДЛЯ ВСТАВКИ ФАЙЛА |
|
|
InsertFileEx.js
| Code: | ///Inserts the selected text file into the current file
///Вставка выбранного текстового файла в текущий
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1357#1357
// Version: 1.10 (2011.07.21)
//
// -"Вставить\Файл..." Call("Scripts::Main", 1, "InsertFileEx.js", `"%f"`)
var fileName = WScript.Arguments(0);
if (fileName == AkelPad.GetEditFile(0))
{
//Диалог открытия файла
if (! AkelPad.Include("CommonFunctions.js")) WScript.Quit();
fileName = FileDialogDefault(true, fileName, GetFileExt(fileName));
}
if (fileName)
{
//Считывание содержимого файла
var fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso.FileExists(fileName))
{
//Считывание содержимого файла
var Content = AkelPad.ReadFile(fileName);
//Запись содержимого в окно редактирования Akel'а
AkelPad.ReplaceSel(Content);
}
} |
Реализовал вставку файла по своей же просьбе (п.2)
NB: Для работы данного кода обязателен CommonFunctions.js.
Скрипт работает в т.ч. из меню последних файлов; его нужно вызывать с парамертом "%f"!
Updated: скрипт отредактирован с учётом пожеланий уважаемого wisgest'а по открытию файла на JavaScript и по по вставке в юникоде, а также вставлена проверка на наличие файла...
Last edited by VladSh on Thu Jul 21, 2011 9:58 am; edited 17 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Wed Jul 18, 2007 6:10 pm Post subject: Скрипт копирует в буфер обмена полный путь ли дирректорию |
|
|
FilePathCopyToCB.js | Code: | ///Copy to clipboard file name full (%f) or file directory (%d)
///Копирование полного имени файла (%f) или папки (%d) в буфер обмена
// Version: 1.1 (2010.07.30)
if (WScript.Arguments.length)
AkelPad.SetClipboardText(WScript.Arguments(0)); |
Пример использования в ContextMenu:
| Code: | "Copy to Clipboard"
{
-"FileName Full" Call("Scripts::Main", 1, "FilePathCopyToCB.js", `"%f"`)
-"FileDir" Call("Scripts::Main", 1, "FilePathCopyToCB.js", `"%d"`)
} |
FileNameCopyToCB.js | Code: | ///Copy to clipboard file name short (%f)
///Копирование только имени файла (%f) в буфер обмена
// Version: 1.1 (2010.07.30)
// -"Только имя" Call("Scripts::Main", 1, "FileNameCopyToCB.js", `"%f"`)
if (WScript.Arguments.length)
AkelPad.SetClipboardText(GetFileName(WScript.Arguments(0)));
function GetFileName(pFile)
{
return pFile.slice(pFile.lastIndexOf('\\') + 1);
} |
Чтобы не держать этот скрипт можно запускать скрипт переименования RenameFileDialog.js, из окошка InputBox копировать существующее имя файла и отменять переименование; совсем как в FS..
Last edited by VladSh on Wed Jul 20, 2011 6:31 pm; edited 11 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Wed Jul 18, 2007 6:14 pm Post subject: |
|
|
Для простого обрамления текста сейчас есть штатный метод Insert().
Для ссылок сделал отдельный скрипт, т.к. он использует более сложный алгоритм:
TagLinking.js | Code: | ///Universal linking selectedText
//example: <a href="SelectedText befor space (URL)">SelectedText after space (Text)</a>
// Version: 2.0 (2010.06.22)
var tags = unescape(WScript.Arguments(0)).split('#');
var SelText = AkelPad.GetSelText();
var iSpace = SelText.indexOf(' ', 0);
var sCaption = SelText.substr(iSpace + 1);
var sURL = SelText.substring(0, iSpace);
if (sURL == '') sURL = sCaption;
AkelPad.ReplaceSel( tags[0] + sURL + tags[1] + sCaption + tags[2] ); |
Примеры вызовов скрипта из ContextMenu см. здесь.
Last edited by VladSh on Mon Aug 02, 2010 12:14 pm; edited 18 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Fri Jul 20, 2007 10:48 am Post subject: ?????????????????? -> normal text |
|
|
Иногда текст, вставляемый из буфера обмена, имеет нечитаемый вид, типа того: ?????? ????????? ????????????????
Такое встречается при копировании текста из старых (часто - из DOS'овских) доков или прог.
Для этого написал такой скриптик. Алгоритм прост до безобразия: создаётся новая вкладка, вставляется текст из буфера обмена, выделяется всё и копируется обратно в буфер обмена, вкладка закрывается. Если вставить текст из буфера снова, то он будет в нормальной, читаемой кодировке.
Чуть переделал скрипт на исправление текста в виде "умляутов", подробнее см. комменты в скрипте.
CorrectCBCodepage.js | Code: | ///Correction of Cyrillic characters of Clipboard
///Корректировка кириллических символов буфера обмена
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1413#1413
// Version: 2.2 (2011.07.20)
//Создание (закладки) нового файла
AkelPad.Command(4101);
//это работало при вставке текста в виде вопросиков; добавил следующую строку, когда попадётся такая строка, то надо проверить, работает ли это при ней, и если нет, тогда думать, как заставить скрипт работать в 2-х вариантах
//AkelPad.ReplaceSel(AkelPad.GetClipboardText());
//корректировка текста в виде "умляутов" (такой текст гораздо чаще бывает); см. http://akelpad.sourceforge.net/forum/viewtopic.php?p=1306#1306
AkelPad.Command(4191);
AkelPad.SetSel(0, -2);
AkelPad.SetClipboardText(AkelPad.GetSelText());
AkelPad.SendMessage(AkelPad.GetMainWnd(), 1229 /*AKD_SETMODIFY*/, 0, false); //помечаем как неизменявшийся, чтобы не спрашивало, сохранить или нет
AkelPad.Command(4318); //закрываем текущую вкладку |
Last edited by VladSh on Wed Jul 20, 2011 10:56 am; edited 17 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Mon Jul 23, 2007 2:56 pm Post subject: Ещё несколько скриптов |
|
|
insertStructure.js
| Code: | ///Convert selected lines to predefine structure
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1420#1420
// Version: 5.0 (2012.10.04)
//
// Parameters:
// -shift - lines shift to the right:
// • without this parameter - shift from program settings;
// • "" / "\t" or other value
//
// Examples:
// • HTML (ul):
// -"<ul>...</ul>" Call("Scripts::Main", 1, "insertStructure.js", `-rootOpen="<ul>" -lineOpen="<li>" -lineClose="</li>" -rootClose="</ul>"`)
// • fb2 (stanza);
// • BbCode (list):
// -"[list]...[/list]" Call("Scripts::Main", 1, "insertStructure.js", `-rootOpen="[list]" -lineOpen="[*]" -rootClose="[/list]" -shift=""`)
if (AkelPad.IsAkelEdit()) {
if (WScript.Arguments.length == 0) WScript.Quit();
if (! AkelPad.Include("selCompleteLine.js")) WScript.Quit();
oCh.runWithRedraw();
}
function process() {
var rootOpen = AkelPad.GetArgValue("rootOpen", "");
var lineOpen = AkelPad.GetArgValue("lineOpen", "");
var lineClose = AkelPad.GetArgValue("lineClose", "");
var rootClose = AkelPad.GetArgValue("rootClose", "");
if (AkelPad.GetArgLine().indexOf("-shift") != -1) {
sShift = escSequencesProcessing(AkelPad.GetArgValue("shift", ""));
}
else
getShift();
lineOpen = sShift + lineOpen;
oCh.setCompleteLineText();
var spaces = oCh.Text.match(/^[ \t]*/)[0];
if (rootOpen) rootOpen = spaces + rootOpen + "\r";
if (rootClose) rootClose = "\r" + spaces + rootClose;
var lines = oCh.Text.replace(/^([ \t]*)(\S)/mg, "$1" + lineOpen + "$2").replace("\r", lineClose + "\r") + lineClose;
if (!oCh.Text)
lines = lineOpen + lines;
oCh.Text = rootOpen + lines + rootClose;
} | Старые названия этого скрипта HTMLul.vbs, HTMLul.js и XMLStructure.js.
Благодарности: Infocatcher, FeyFre
NB: This script used selCompleteLine.js.
Last edited by VladSh on Thu Oct 04, 2012 1:07 pm; edited 26 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Sun Jul 29, 2007 12:37 pm Post subject: |
|
|
NewFilebyRecent.js
| Code: | ///Creation of a new file on the basis of the contained allocated file in the list of the fresh
///Универсальное создание нового файла на основе имеющегося в окне редактирования или в списке свежих
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1505#1505
// Version: 2.8 (2012.09.11)
//
// -"Новый на основе выбранного" Call("Scripts::Main", 1, "NewFilebyRecent.js", `"%f"`) Icon("%a\AkelFiles\Plugs\ToolBar.dll", 1) - из меню свежих файлов (параметр `"%f"` обязателен!)
// -"Новый на основе текущего" Call("Scripts::Main", 1, "NewFilebyRecent.js") Icon("%a\AkelFiles\Plugs\ToolBar.dll", 1) - меню вкладок, окна редактирования или тулбара
var fileName = "";
var ext = "";
var fso = new ActiveXObject("Scripting.FileSystemObject");
var pContent = "";
if (WScript.Arguments.length) {
if (WScript.Arguments(0) != AkelPad.GetEditFile(0))
fileName = WScript.Arguments(0); //стартовали из меню списка свежих!
}
if (fileName) {
//Создание на основе выделенного в списке свежих
if (fso.FileExists(fileName)) {
//Считывание содержимого файла
pContent = AkelPad.ReadFile(fileName)
}
ext = fso.GetExtensionName(fileName);
}
else {
//Стартовали из меню вкладок или окна редактирования
//Пытаемся сначала взять выделенный текст и на основе его создать док, иначе создаём на основе всего текста файла текущей вкладки
pContent = AkelPad.GetSelText() || AkelPad.GetTextRange(0, -1);
}
if (AkelPad.Include("CommonFunctions.js"))
CreateByFile(0, ext); //создаём со всеми параметрами исходного файла
else
AkelPad.Command(4101 /*IDM_FILE_NEW*/);
//Запись содержимого в окно редактирования Akel'а
AkelPad.ReplaceSel(pContent);
//Установка курсора в начало нового файла
AkelPad.SetSel(0, 0); |
This script used CommonFunctions.js.
Last edited by VladSh on Tue Sep 11, 2012 11:38 am; edited 24 times in total |
|
| Back to top |
|
 |
Idjo
Joined: 06 May 2007 Posts: 21
|
Posted: Sun Aug 05, 2007 2:50 pm Post subject: |
|
|
ShiftRight.js & ShiftLeft.js
Shifts selected rows.
The shift string can be defined, and if you define it as "//" it can be used to turn rows into comments.
JS is preety new for me so I'd like to have comments.
Update: Fixed by Instructor's suggestion.
ShiftRight.js
| Code: | var sShift=" "; //Shift definition (\t for tab)
//var AkelPad=new ActiveXObject("AkelPad.document");
var nSelStart=AkelPad.GetSelStart();
var nSelEnd= AkelPad.GetSelEnd();
var sSelText= AkelPad.GetSelText();
//Find row start
var hEditWnd=AkelPad.GetEditWnd();
var nMinLine=AkelPad.SendMessage(hEditWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nSelStart);
var nMinLineIndex=AkelPad.SendMessage(hEditWnd, 187 /*EM_LINEINDEX*/, nMinLine, 0);
AkelPad.SetSel(nMinLineIndex,nSelEnd);
//First row's shifting
var sContent=AkelPad.GetSelText();
var sNewContent=sShift;
nSelStart+=sShift.length;
//Other rows' shifting
while (sContent.length > 1)
{
if (sContent.charAt(0)=="\r")
sNewContent+="\r"+sShift;
else
sNewContent+=sContent.charAt(0);
sContent=sContent.slice(1);
}
sNewContent+=sContent.charAt(0);
AkelPad.ReplaceSel(sNewContent);
AkelPad.SetSel(nSelStart,AkelPad.GetSelEnd()); |
ShiftLeft.js
| Code: | var sShift=" "; //Shift definition (\t for tab)
//var AkelPad=new ActiveXObject("AkelPad.document");
var nSelStart=AkelPad.GetSelStart();
var nSelEnd= AkelPad.GetSelEnd();
var sSelText= AkelPad.GetSelText();
//Find row start
var hEditWnd=AkelPad.GetEditWnd();
var nMinLine=AkelPad.SendMessage(hEditWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nSelStart);
var nMinLineIndex=AkelPad.SendMessage(hEditWnd, 187 /*EM_LINEINDEX*/, nMinLine, 0);
AkelPad.SetSel(nMinLineIndex,nSelEnd);
//First row's shifting
var sContent=AkelPad.GetSelText();
var sNewContent="";
if (sContent.slice(0,sShift.length)==sShift)
{
sContent=sContent.slice(sShift.length);
nSelStart=Math.max(nSelStart-sShift.length,nMinLineIndex);
}
//Other rows' shifting
while (sContent.length > 0)
{
if (sContent.slice(0,1+sShift.length)=="\r"+sShift)
{
sNewContent+="\r";
sContent=sContent.slice(1+sShift.length);
}
else
{
sNewContent+=sContent.charAt(0);
sContent=sContent.slice(1);
}
}
AkelPad.ReplaceSel(sNewContent);
AkelPad.SetSel(nSelStart,AkelPad.GetSelEnd()); |
Last edited by Idjo on Sun Aug 05, 2007 10:41 pm; edited 2 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Mon Aug 06, 2007 12:27 pm Post subject: CommonFunctions |
|
|
CommonFunctions.js | Code: | ///Script "library" for working with for WinFS
// must be placed in ...\Scripts\Include\
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1582#1582
// Version: 2.8 (2012.11.22)
//Default variables
var pSlash = "\\";
var pExtTXT = "txt";
var pDefaultExt; //можно задать извне, это будет приоритетнее, т.е. не заменится при вызове функции
//FUNCTIONS
//определение расширения по умолчанию
function getDefaultExt() {
if (!pDefaultExt) {
var lParam;
if (lParam = AkelPad.MemAlloc(256)) {
AkelPad.SendMessage(AkelPad.GetMainWnd(), 1222 /*AKD_GETMAININFO*/, 224 /*MI_DEFAULTSAVEEXT*/, lParam);
pDefaultExt = AkelPad.MemRead(lParam, 1 /*DT_UNICODE*/);
AkelPad.MemFree(lParam);
}
}
return pDefaultExt || pExtTXT;
}
//Вызов диалога Открытия/Сохранения файла (WinAPI) с предварительной обработкой и инициализацией всех необходимых параметров
function FileDialogDefault(bOpenTrueSaveFalse, pInitialFile, pInitialExt) {
var pInitialDir = GetParentClosed(pInitialFile);
//<определение фильтров>
var nFilterIndex = 1; //номер фильтра по порядку (не индекс!) для arrExtLines; по умолчанию считаем, что расширение пока не найдено..
var arrExtAll;
var arrExtLines = [];
arrExtAll = getFileContent(AkelPad.GetAkelDir(5) + "\\Params\\" + "FileDialogExtentions.param", "\r\n");
if (arrExtAll) {
var n = 0;
var arrFTypeInfo;
for (var i = 0, l = arrExtAll.length; i < l; i++) {
arrFTypeInfo = arrExtAll[i].split("=");
arrExtAll[i] = getFilter(arrFTypeInfo[0], arrFTypeInfo[1]);
if (!n) {
if ((";" + arrFTypeInfo[1] + ";").split(";" + pInitialExt + ";").length == 2) { //если есть точное совпадение расширения, то полный список не нужен
if (bOpenTrueSaveFalse) {
nFilterIndex = i + 1;
n = 1;
}
else {
n += 1;
arrExtLines[n] = arrExtAll[i];
break;
}
}
}
}
if (bOpenTrueSaveFalse)
arrExtLines = arrExtAll;
else {
if (n == 1) {
arrExtLines[0] = arrExtAll[0];
nFilterIndex = 2;
}
else {
arrExtLines = arrExtAll; //не нашли расширение в списке
nFilterIndex = -1;
}
}
}
else { //если файл со списком типов не существует или пуст
arrExtLines[0] = getFilter("All Files", "*");
arrExtLines[1] = getFilter("Plain Text files", pExtTXT);
if (pInitialExt) {
if (pInitialExt != pExtTXT) { //если это расширение не txt, значит вручную добавляем его..
arrExtLines[2] = getFilter(pInitialExt.toUpperCase() + " files", pInitialExt);
nFilterIndex = 3;
}
else
nFilterIndex = 2;
}
}
var pFilter = arrExtLines.join("");
//</определение фильтров>
//если расширение точно определено в списке, то в имени файла его выдавать не надо
if (nFilterIndex > 0) {
var sExtTmp = GetFileExt(pInitialFile);
if (sExtTmp && ((sExtTmp != pInitialExt) || (nFilterIndex == 1))) //если был выделен файл с расширением, отличающимся от текущего файла - выдаём, чтобы пользователь мог подтвердить или исправить
pInitialFile = GetFileName(pInitialFile) || "filename";
else
pInitialFile = GetFileNameOnly(pInitialFile);
}
else {
nFilterIndex = 1;
if (!bOpenTrueSaveFalse) {
if (pInitialExt)
pInitialFile = GetFileNameOnly(pInitialFile) + "." + pInitialExt; //если расширение определено, но отсутствует в списке, то выдаём его в имени файла
pInitialExt = getDefaultExt(); //для того, чтобы при неопределении расширения файла он не сохранялся без расширения
}
}
return FileDialog(bOpenTrueSaveFalse, AkelPad.GetMainWnd(), pInitialDir, pInitialFile, pInitialExt, pFilter, nFilterIndex);
}
//Сборка фильтра
function getFilter(sFTypeInfo, sExts /*расширения ч/з ";"*/) {
var sMask = "*." + (sExts).replace(/;/g, ";*."); //маска для всех расширений этого типа, без пробелов
return sFTypeInfo + " (" + sMask.replace(/;/g, "; ") + ")\0" + sMask + "\0"; //фильтр в полном виде
}
//Стандартный диалог Открытия/Сохранения файла (WinAPI)
function FileDialog(bOpenTrueSaveFalse, hWnd, pInitialDir, pInitialFile, pInitialExt, pFilter, nFilterIndex) {
var nFlags = 0x880804; //OFN_HIDEREADONLY|OFN_PATHMUSTEXIST|OFN_EXPLORER|OFN_ENABLESIZING
var lpStructure;
var lpFilterBuffer;
var lpFileBuffer;
var lpExtBuffer;
var lpDirBuffer;
var oSys;
var pResultFile = "";
var nCallResult;
var lFilterBuffer = pFilter.length; //передаём не 256, а реальный размер pFilter
if (lpFilterBuffer = AkelPad.MemAlloc((lFilterBuffer+1) * _TSIZE)) {
AkelPad.MemCopy(lpFilterBuffer, pFilter.substr(0, lFilterBuffer), _TSTR);
if (lpFileBuffer = AkelPad.MemAlloc(256 * _TSIZE)) {
AkelPad.MemCopy(lpFileBuffer, pInitialFile.substr(0, 255), _TSTR);
if (lpExtBuffer = AkelPad.MemAlloc(256 * _TSIZE)) {
AkelPad.MemCopy(lpExtBuffer, pInitialExt.substr(0, 255), _TSTR);
if (lpDirBuffer = AkelPad.MemAlloc(256 * _TSIZE)) {
AkelPad.MemCopy(lpDirBuffer, pInitialDir.substr(0, 255), _TSTR);
if (lpStructure = AkelPad.MemAlloc(_X64?136:76)) {
//Fill structure
AkelPad.MemCopy(lpStructure, _X64?136:76, 3 /*DT_DWORD*/); //lStructSize
AkelPad.MemCopy(lpStructure + (_X64?8:4), hWnd, 2 /*DT_QWORD*/); //hwndOwner
AkelPad.MemCopy(lpStructure + (_X64?24:12), lpFilterBuffer, 2 /*DT_QWORD*/); //lpstrFilter
AkelPad.MemCopy(lpStructure + (_X64?44:24), nFilterIndex, 3 /*DT_DWORD*/); //nFilterIndex
AkelPad.MemCopy(lpStructure + (_X64?48:28), lpFileBuffer, 2 /*DT_QWORD*/); //lpstrFile
AkelPad.MemCopy(lpStructure + (_X64?56:32), 256, 3 /*DT_DWORD*/); //nMaxFile
AkelPad.MemCopy(lpStructure + (_X64?68:44), lpDirBuffer, 2 /*DT_QWORD*/); //lpstrInitialDir
AkelPad.MemCopy(lpStructure + (_X64?96:52), nFlags, 3 /*DT_DWORD*/); //Flags
AkelPad.MemCopy(lpStructure + (_X64?104:60), lpExtBuffer, 2 /*DT_QWORD*/); //lpstrDefExt
if (oSys = AkelPad.SystemFunction()) {
//Call dialog
if (bOpenTrueSaveFalse == true)
nCallResult = oSys.Call("comdlg32::GetOpenFileName" + _TCHAR, lpStructure);
else
nCallResult = oSys.Call("comdlg32::GetSaveFileName" + _TCHAR, lpStructure);
//Result file
if (nCallResult) pResultFile = AkelPad.MemRead(lpFileBuffer, _TSTR);
}
AkelPad.MemFree(lpStructure);
}
AkelPad.MemFree(lpDirBuffer);
}
AkelPad.MemFree(lpExtBuffer);
}
AkelPad.MemFree(lpFileBuffer);
}
AkelPad.MemFree(lpFilterBuffer);
}
return pResultFile;
}
// Определение основных характеристик формата файла
function getFileFormat(hWnd /*hWndEdit*/) {
return {
cp: AkelPad.GetEditCodePage(hWnd), // CodePage
BOM: AkelPad.GetEditBOM(hWnd),
nl: AkelPad.GetEditNewLine(hWnd) // NewLine
};
}
///Создание вкладки нового файла со всеми параметрами исходного файла
function CreateByFile(hWnd /*hWndEdit*/, pExt /*расширение, для установки подстветки; если "", будет пытаться определить автоматически*/) {
var fileFormat = getFileFormat(hWnd);
// пытаемся определить расширение для установки нужной подсветки
var bCoderInclude = AkelPad.Include("CoderFunctions.js");
if (!pExt && bCoderInclude)
pExt = GetSyntaxAliasExtension();
AkelPad.Command(4101 /*IDM_FILE_NEW*/); //создание (закладки) для сохранения выделения отдельным файлом
AkelPad.SaveFile(0, "", fileFormat.cp, fileFormat.BOM); //выставление кодировки как у исходного файла
AkelPad.SendMessage(AkelPad.GetMainWnd(), 1230 /*AKD_SETNEWLINE*/, 0, fileFormat.nl); //выставление "формата новой строки" как у исходного файла
// пытаемся выставить нужную подсветку
if (pExt && bCoderInclude) SetSyntax(pExt);
}
//Разбивает полный путь в массив [Папка, Имя_файла, Расширение]
function SeparateFile(pFile) {
var pPath = "";
var pFileName = "";
var pFileExt = "";
var pos = pFile.lastIndexOf(pSlash);
if (pos != -1)
pPath = pFile.slice(0, pos + 1);
pFileName = pFile.slice(pos + 1);
if (pFileName) {
pos = pFileName.lastIndexOf(".");
if (pos != -1)
{
pFileExt = pFileName.slice(pos + 1);
pFileName = pFileName.slice(0, pos);
}
}
return {
path: pPath,
name: pFileName,
ext: pFileExt
};
}
//Возвращает полное имя папки БЕЗ закрывающего \
function GetParent(pFile) {
var pDir = "";
var pozLastSep = pFile.lastIndexOf(pSlash);
if (pozLastSep != -1)
pDir = pFile.slice(0, pozLastSep);
return pDir;
}
//Возвращает полное имя папки С закрывающим \
function GetParentClosed(pFile) {
var pDir = GetParent(pFile);
if (pDir) pDir = pDir + pSlash;
return pDir;
}
//Возвращает имя файла С расширением
function GetFileName(pFile) {
return pFile.slice(pFile.lastIndexOf(pSlash) + 1);
}
//Возвращает имя файла БЕЗ расширения
function GetFileNameOnly(pFile) {
var pFileName = GetFileName(pFile);
var pos = pFileName.lastIndexOf(".");
if (pos != -1)
pFileName = pFileName.slice(0, pos);
return pFileName;
}
//Возвращает расширение файла
function GetFileExt(pFile) {
var ext = "";
var pos = pFile.lastIndexOf(".");
if (pos != -1) ext = pFile.substr(pos + 1);
return ext;
}
//Remove inadmissible symbols (from wisgest)
function CorrectFileName(pFileNameOnly) {
pFileNameOnly = pFileNameOnly.replace(/\t/g, " "); //валим табуляции, т.к. диалог с ними иногда просто не отображается
pFileNameOnly = pFileNameOnly.replace(/ /g, " "); //убираем повторяющиеся пробелы
return pFileNameOnly.replace(/[\\\/:\*\?"{}<>\|]/g, "");
}
function CorrectFileNameFull(pFile) {
pFileNameOnly = GetFileName(pFile);
pFileNameOnly = CorrectFileName(pFileNameOnly);
return GetParent(pFile) + pSlash + pFileNameOnly;
}
//Получает содержимое файла; возвращает:
//если файла нет - undefined; если pSepRow не передан - возвращает содержимое в виде строки; если передан - возвращает массив, разбитый через pSepRow
function getFileContent(pFile, pSepRow) {
var result;
var fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso.FileExists(pFile) == true) {
result = AkelPad.ReadFile(pFile);
if (pSepRow.length != 0)
result = result.split(pSepRow);
}
return result;
} |
Для вывода типов файлов в диалогах открытия/сохранения файла можно пользоваться файлом параметров, который должен находиться в ..\Scripts\Params\:
FileDialogExtentions.param | Code: | All Files=*
Plain Text files=txt
AkelPad Coder files=coder
AkelPad Param=param
AkelPad SpellCheck files=spck
ASM files=asm;inc
Bash files=sh;csh;bsh
Basic files=bas;frm;cls
BbCode files=bbc
Config files=ini;inf;cfg
C files=c;inl;h
C# files=cs
C++ files=c;cpp;cxx;hpp;hxx;inl;h
CSS files=css
DOS/NT Batch files=bat;cmd
Haskell files=hs;lhs
HE Java Script files=hejs
HE VB Script files=hevbs
HTML files=html;htm
Info files=log;nfo
IDL files=idl
Java files=java;jav
Java Script files=js
Lisp files=lsp;lisp
Lotus Script files=lss
Lotus @-formula files=l@
Lotus XML files=dxl
Menu files=mnu
Pascal files=pas;inc;def;dfm
Perl files=cgi;pl;pm;plx
PHP files=php;php3
PL/SQL files=sql
Python files=py;pyw
Resource Script files=rc;rc2
Ruby files=rb;rbw
T/SQL files=sql;tql
Visual Basic files=vb
Visual Basic Script files=vbs
Windows Registry files=reg
XML files=xml;xhtml
XSLT files=xslt;xsl |
Обязательное условие: первым должен идти "All Files", 2-м - txt.
Хоть размер фильтра теперь в скрипте и вычисляется, но я не советую мучать животное этим монструозным списком, лучше уж выбрать то, чем реально пользуешься.
Для наполнения этого списка (чтобы "всё было" ) присылайте варианты в личку.
Common "lib" for used in other scripts.
Has edited it is a little, it is final on the basis of scripts Instructors - a convenient piece as it has appeared Now I use in many scripts thanks to what their size has considerably decreased.
Благодарности:
- wisgest'у за предложение по функции CorrectFileName;
- Instructor'у за InsertFile.js из диструбутива Scripts-плагина, на основе которого были написаны FileDialogDefault и FileDialog и за замечания;
- FeyFre за помощь по lpstrInitialDir.
Last edited by VladSh on Thu Nov 22, 2012 1:14 pm; edited 47 times in total |
|
| Back to top |
|
 |
VladSh
Joined: 29 Nov 2006 Posts: 2510 Location: Киев, Русь
|
Posted: Mon Aug 06, 2007 12:44 pm Post subject: My variant Rename file with dialog |
|
|
RenameFileDialog.js | Code: | ///Rename current editing file with dialog
///Переименование текущего файла
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1584#1584
// Version: 2.9 (2012.11.22)
//
// Аргумент -ext (1/0) - по умолчанию (1) отображает в окошке расширение, (0) - не отображает
// -"RenameFile..." Call("Scripts::Main", 1, "RenameFileDialog.js", `"-ext=0"`) - меняет только имя файла
//
// - если необходимо заменить имя файла с расширением, то необходимо в окошке дописать к имени файла новое расширение;
// - если необходимо удалить расширение, то после имени файла достаточно поставить точку
var hMainWnd = AkelPad.GetMainWnd();
var fileNameFull = AkelPad.GetEditFile(0);
if (fileNameFull) { //File already exist
if (! AkelPad.Include("CommonFunctions.js")) WScript.Quit();
var useExt = AkelPad.GetArgValue("ext", 1);
var File = SeparateFile(fileNameFull);
var extInfo = "";
var fileSelect;
if (useExt == true && File.ext)
fileSelect = File.name + "." + File.ext;
else {
fileSelect = File.name;
if (File.ext) extInfo = " for *." + File.ext;
}
var pScriptName = WScript.ScriptName;
var Prompt = "New name" + extInfo + ":";
var fileSelectNew = "";
var fileNameNew = "";
var fso;
var fileExist;
if (hMainWnd) {
fso = new ActiveXObject("Scripting.FileSystemObject");
do {
fileSelectNew = AkelPad.InputBox(hMainWnd, pScriptName, Prompt, fileSelect);
if (fileSelectNew) {
fileSelectNew = CorrectFileName(fileSelectNew); //Remove special symbols
if (useExt == true || File.ext == "" || fileSelectNew.lastIndexOf(".") != -1)
fileNameNew = fileSelectNew;
else
fileNameNew = fileSelectNew + "." + File.ext;
var fileNameFullNew = File.path + fileNameNew;
if (fileSelectNew != "" & (fileNameFullNew != fileNameFull)) {
fileExist = fso.FileExists(fileNameFullNew);
if (fileExist == false) { //Check already newFileName existent
var nSelStart = AkelPad.GetSelStart();
var nSelEnd = AkelPad.GetSelEnd();
var curFileFormat = getFileFormat(AkelPad.GetEditWnd());
AkelPad.Command(4324); //Close editing file
if (AkelPad.GetEditFile(0) != fileNameFull) { //Check noCANCEL click for changed document!
var Err;
//Rename file
try {fso.MoveFile(fileNameFull, fileNameFullNew);}
catch(e) {
Err = e;
fileNameFullNew = fileNameFull;
}
if (fso.FileExists(fileNameFullNew) == true) {
//Open file
AkelPad.OpenFile(fileNameFullNew, 0, curFileFormat.cp, curFileFormat.BOM);
//Recovery selection
AkelPad.SetSel(nSelStart, nSelEnd);
}
if (Err) {
if (0x100000000 + Err.number == 0x800a0046)
AkelPad.MessageBox(hMainWnd, "Insufficient rights, or file is locked by another application!", "AkelPad -> " + WScript.ScriptName, 48);
else
throw Err;
}
}
}
else {
Prompt = "File '" + fileNameNew + "' already exist! Input other filename" + extInfo + ":";
}
}
}
else {
break;
}
}
while (fileExist);
}
}
else //File is new - try new document save
AkelPad.Command(4106) |
Примеры использования:
В контекстном меню окна редактирования поставил новый вызов:
| Code: | | -"Rename File..." Call("Scripts::Main", 1, "RenameFileDialog.js", `"-ext=0"`) |
А в контекстном меню вкладок оставил старый:
| Code: | | -"Rename File..." Call("Scripts::Main", 1, "RenameFileDialog.js") |
Реализована логика, которую я собственно и хотел с самого начала.
N.B.: Для работы данного кода обязателен CommonFunctions.js.
Last edited by VladSh on Thu Nov 22, 2012 1:15 pm; edited 25 times in total |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|