Jump to content
Sign in to follow this  
BugFix

SciTE - Internet search in the editor based by search engine or search site.

Recommended Posts

This lua script gives you the ability, to search for selected text or word from cursor in an search engine or on an search site of your choice.You can select the engine/site from a list, that you have defined in your user properties.

To get the right call for your search engine, open the engine and search for one word. You need the url without the searched word. Write to your properties an display name for this engine and, separated by a comma, the url. See my example in the script header.

For the list with  search sites, you need display name and site address (without http://).

It will searched for the full selected text or, if none selection exists, for the word touched by the cursor. You can allow in the properties, that also will recognized words with dots (like objVar.Property).

The script uses the shell.dll. But if you don't have installed it, the browser will opened with an command line call. Thats why the command window will pop up for a short moment.

You'll find details for installation and key bindings inside the script. Look for free command numbers in SciTE. By default installation, the numbers must be greater than 35 (max. 49).

-- TIME_STAMP   2018-09-02 09:22:03

--[[

	This script publicates two functions
	- InetSearch.Engine()
	  You can search for the selected/touched text in SciTE and can select a search engine of your choice.

	- InetSearch.Site()
	  You can search for the selected/touched text in SciTE with a defined search engine and can select a search site of your choice.

	Copy this script in your Lua scripts folder.
	Load this file in the Lua startup: dofile("Full\\Path\\InetSearch.lua")

	Add
	in "SciTEUser.properties" the following properties with search engines and search sites of your choice:

	#~ Inet Search Settings
	#~ List of engines. "display-name,search-url" (if not set: google.com will used)
	#~ If only one entry exists, the selection box will not shown.
	Inet.Search.Engines= \
	Google,https://www.google.de/search?q=| \
	MetaGer,https://metager.de/meta/meta.ger3?focus=web&eingabe=| \
	Bing,https://www.bing.com/search?q=| \
	Ask,https://de.ask.com/web?q=| \
	Yandex,https://www.yandex.com/search/?text=

	#~ Engine for site based search
	#~ Use display name from engines list (if not set: google.com will used)
	Inet.Search.SearchOnSite.Engine=Google

	#~ List of sites for site based search. "display-name,site-url"
	#~ If not set, it searches without a special site.
	#~ If only one entry exists, the selection box will not shown.
	Inet.Search.SearchOnSite.Sites= \
	AutoIt DE,autoit.de| \
	AutoIt EN,autoitscript.com| \
	MSDN,msdn.microsoft.com

	#~ By default, words will detected without dots. (0)
	#~ You can allow dots, to detect object variables with properties or methods too.
	Inet.Search.Allow.Punctuation=1

	#~ Search commands
	#~ Search word from cursor with engine selection
	command.name.9.*=Search with engine selection
	command.9.*=dostring InetSearch.Engine()
	command.mode.9.*=subsystem:lua,savebefore:no
	command.shortcut.9.*=Ctrl+Shift+F8

	#~ Search word from cursor with search site selection
	command.name.5.*=Search with site selection
	command.5.*=dostring InetSearch.Site()
	command.mode.5.*=subsystem:lua,savebefore:no
	command.shortcut.5.*=Ctrl+Shift+F9

--]]


InetSearch = {}
InetSearch.Handler = EventClass:new(Common)


do
	------------------------------------------------------------------------------------------------
	local engineFallback = "Google,https://www.google.com/search?q="  -- default search engine: "display-name,search-url"
	local search_type    = nil
	local engine_url     = nil
	local search_item    = nil
	local search_site    = nil
	local tableSelection = nil
	local list_type      = 16
	------------------------------------------------------------------------------------------------

	------------------------------------------------------------------------- Load library protected
	local require_protected = function(_lib)
		local loaded_lib
		if pcall(function() loaded_lib = require(_lib)  end) then return loaded_lib
		else return nil end
	end --> require_protected
	------------------------------------------------------------------------------------------------
	local shell = require_protected("shell")                    -- loads the shell library if exists
	------------------------------------------------------------------------------------------------

	------------------------------------------------------------------------------ Starts the search
	local RunSearch  = function(_item, _url, _site)
		local sSite = ''
		if _site ~= nil then sSite = "%20site:".._site end
		local sCmd = _url.._item..sSite
		if shell then shell.exec(sCmd)
		else os.execute('start "" "'..sCmd..'"') end
	end --> RunSearch
	------------------------------------------------------------------------------------------------

	----------------------------------------------------------------------------- Show the user list
	local ShowSelectionList = function()
		-- create the selection list (display names from engines or sites)
		local sep, list = '_', tableSelection[1][1]
		for i = 2, #tableSelection do
			list = list..sep..tableSelection[i][1]
		end
		local sep_tmp = editor.AutoCSeparator
		editor.AutoCSeparator = string.byte(sep)
		editor:UserListShow(list_type, list)
		editor.AutoCSeparator = sep_tmp
	end --> ShowSelectionList
	------------------------------------------------------------------------------------------------

	--------------------------------------------------------------------------- Select the user list
	function InetSearch.Handler:OnUserListSelection(_tp, _sel)
		if _tp == list_type then
			local url
			for i = 1, #tableSelection do
				if tableSelection[i][1] == _sel then
					url = tableSelection[i][2]
					break
				end
			end
			if search_type == 'site' then
				search_site = url
			else
				search_site = nil
				engine_url = url
			end
			RunSearch(search_item, engine_url, search_site)
		end
	end
	------------------------------------------------------------------------------------------------

	--------------------------------------------------------- List of search engines from properties
	local GetEngines = function()
		local sEngines = props['Inet.Search.Engines']
		-- without settings, the default search engine will used
		if sEngines == '' then sEngines = engineFallback end
		local tEngines = {}
		for entry in sEngines:gmatch('([^|]+)|-') do
			for name, url in entry:gmatch('([^,]+),(.+)') do
				table.insert(tEngines, {name, url})
			end
		end
		return tEngines
	end --> GetEngines
	------------------------------------------------------------------------------------------------

	----------------------------------------------------------- List of search sites from properties
	local GetSearchSites = function()
		local sSites = props['Inet.Search.SearchOnSite.Sites']
		if sSites == '' then return nil end
		local tSites = {}
		for entry in sSites:gmatch('([^|]+)|-') do
			for name, url in entry:gmatch('([^,]+),(.+)') do
				table.insert(tSites, {name, url})
			end
		end
		return tSites
	end --> GetSearchSites
	------------------------------------------------------------------------------------------------

	-------------------------------------------------------------------------------- Get search item
	local GetSearchItem = function()
		local sSelect = editor:GetSelText()
		if sSelect ~= '' then return sSelect end

		local allowDots = false
		if props['Inet.Search.Allow.Punctuation'] == '1' then allowDots = true end

		local caret = editor.CurrentPos
		local iLine = editor:LineFromPosition(caret)
		local iZero = editor:PositionFromLine(iLine)
		editor:LineEnd()
		local iLineEnd = editor.CurrentPos
		editor.CurrentPos = caret
		editor:SetSelection(caret,caret)

		local iStart = editor:WordStartPosition(caret)
		if allowDots then
			while iStart > iZero and editor:textrange(iStart -1, iStart) == '.' do
				iStart = editor:WordStartPosition(iStart -1)
			end
		end
		local iEnd = editor:WordEndPosition(caret)
		if allowDots then
			while iEnd < iLineEnd and editor:textrange(iEnd, iEnd +1) == '.' do
				iEnd = editor:WordEndPosition(iEnd +1)
			end
		end
		sSelect = editor:textrange(iStart, iEnd):gsub('^([^%w]+)', ''):gsub('([^%w]+)$', '')

		return sSelect
	end --> GetSearchItem
	------------------------------------------------------------------------------------------------

	------------------------------------------------------------------- Search with engine selection
	local SearchEngineBased = function()
		search_type = 'engine'
		search_item = GetSearchItem()
		if search_item == '' then return nil end
		tableSelection = GetEngines()
		-- only one entry: selection box will not shown
		if #tableSelection == 1 then
			RunSearch(search_item, tableSelection[1][2], nil)
		else
			ShowSelectionList()
		end

	end --> SearchEngineBased
	------------------------------------------------------------------------------------------------

	-------------------------------------------------------------- Search with search site selection
	local SearchSiteBased = function()
		search_type = 'site'
		search_item = GetSearchItem()
		if search_item == '' then return nil end
		-- get the default engine for site based searching
		for _, url in engineFallback:gmatch('([^,]+),(.+)') do
			engine_url = url
		end
		-- if is set, use search engine from properties
		local sEngine = props['Inet.Search.SearchOnSite.Engine']
		if sEngine ~= '' then
			local tEngines = GetEngines()
			for i = 1, #tEngines do
				if tEngines[i][1] == sEngine then
					engine_url = tEngines[i][2]
					break
				end
			end
		end
		tableSelection = GetSearchSites()
		-- if none entries for search sites, use simple search
		if tableSelection == nil then
			RunSearch(search_item, engine_url, nil)
		else
			-- only one entry: selection box will not shown
			if #tableSelection == 1 then
				RunSearch(search_item, engine_url, tableSelection[1][2])
			else
				ShowSelectionList()
			end
		end
	end --> SearchSiteBased
	------------------------------------------------------------------------------------------------

	---------------------------------------------------------------------------- Publicate functions
	InetSearch.Engine = SearchEngineBased
	InetSearch.Site = SearchSiteBased
	------------------------------------------------------------------------------------------------
end
----------------------------------------------------------------------------------------------------

 

InetSearch.lua

Edited by BugFix

Best Regards BugFix  

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By BugFix
      The block comment (internal: box comment) in SciTE cannot be toggled.
      I have now created a script that helps. It works with any file type for which the corresponding entries in the properties are created.For toggeling its required to detect, what the user want to do.
      Rules for detection:     - selection starts in an empty line (line break only)         following line begins with comment.box.start ==> action: uncomment         otherwise                                    ==> action: comment     - selection starts in line with text         line begins with comment.box.start           ==> action: uncomment         otherwise                                    ==> action: comment     - selection ends in an empty line AND       the line before begins with comment.box.end    ==> action: both lines are part of comment block, will deleted     - selection ends in line with comment.box.end    ==> action: line will deleted     - At least two lines must be selected, otherwise an error message is output to the console. This means that in nested block comments there is at least one more line between two comment.box.start markers.
      It is recommended to write all block comment settings into "SciTEUser.properties". The setting "comment.box.end.au3" from "SciTEGlobal.properties" is incorrect and must be corrected.
      comment.box.start.au3=#cs #~ If TAB should used as box.middle, define an alternation (e.g. "@Tab"),  #~ "\t" will not recognised as tab if passed as propertie. comment.box.tab.alternation= #~ If you want characters or tab in each line of comment block, define it here. #~ To use TAB, set the alternation variable here: $(comment.box.tab.alternation) comment.box.middle.au3= comment.box.end.au3=#ce Connection to SciTE
      Search a free command number. Use a Hotkey of your choice.
      If you have declared an option for user lua scripts (e.g.: "Lua.User.Scripts.Path=C:\code\lua"), copy the script to this folder.
      Otherwise copy it to a folder of your choice and change the path in the command: "dofile". But backslashes in the path must be masked. ("\\").
      If your path has spaces don't forgot to encapsulate in string delimiters.
      # 24 Toggle Block Comment command.name.24.*=Toggle Block Comment command.24.*=dofile $(Lua.User.Scripts.Path)/BlockComment.lua command.mode.24.*=subsystem:lua,savebefore:no command.shortcut.24.*=Ctrl+Alt+F10  
      Here the lua script:
      -- TIME_STAMP 2020-10-04 18:56:11 v 0.5 --[[ Toggle Block Comments ©BugFix ( autoit[at]bug-fix.info ) For toggeling its required to detect, what the user want to do. Rules for detection: - selection starts in an empty line (line break only) following line begins with comment.box.start ==> action: uncomment otherwise ==> action: comment - selection starts in line with text line begins with comment.box.start ==> action: uncomment otherwise ==> action: comment - selection ends in an empty line AND the line before begins with comment.box.end ==> action: both lines are part of comment block, will deleted - selection ends in line with comment.box.end ==> action: line will deleted - At least two lines must be selected, otherwise an error message is output to the console. Properties: It is recommended to write all block comment settings into SciTEUser.properties. The setting "comment.box.end.au3" from "SciTEGlobal.properties" is incorrect and must be corrected. comment.box.start.au3=#cs #~ If TAB should used as box.middle, define an alternation (e.g. "@Tab"), #~ "\t" will not recognised as tab if passed as propertie. comment.box.tab.alternation= #~ If you want characters or tab in each line of comment block, define it here. #~ To use TAB, set the alternation variable here: $(comment.box.tab.alternation) comment.box.middle.au3= comment.box.end.au3=#ce ]] local BlockComment = { -- variables ext, -- file extension boxStart, -- property: comment.box.start boxMiddle, -- property: comment.box.middle boxEnd, -- property: comment.box.end bMiddle, -- bool: boxMiddle is defined selStart, -- selection start position selEnd, -- selection end position lineStart, -- selection start line number lineEnd, -- selection end line number newText, -- the text that replaces the selection Init = function(self) self.ext = props["FileExt"] self.boxStart = props["comment.box.start."..self.ext] self.boxMiddle = props["comment.box.middle."..self.ext] local tabAlternation = props["comment.box.tab.alternation"] if tabAlternation ~= "" and self.boxMiddle == tabAlternation then self.boxMiddle = "\t" end self.boxEnd = props["comment.box.end."..self.ext] self.bMiddle = not (self.boxMiddle == "") self.selStart = editor.SelectionStart self.selEnd = editor.SelectionEnd self.lineStart = editor:LineFromPosition(self.selStart) self.lineEnd = editor:LineFromPosition(self.selEnd) self.newText = "" end, -- create the line w/wo middle markers NewLine = function(self, _num, _uncmt) local line = editor:GetLine(_num) if _uncmt then -- if second last line has box.end AND last line is empty OR if (_num == self.lineEnd -1 and self:LineIsEnd(_num) and self:LineIsEmpty(_num +1)) or -- if is the last line AND its empty --> stop proceeding (_num == self.lineEnd and self:LineIsEmpty(_num)) then return "" else -- if box.middle exists --> remove it if self.bMiddle then line = line:sub(self.boxMiddle:len()+1) end end else -- add box.middle if exists line = self.boxMiddle..line end return line end, -- checks if line is empty (has only a line break) LineIsEmpty = function(self, _lineNum) return (editor:GetLine(_lineNum) == "\r\n") end, -- checks if line has box.start LineIsStart = function(self, _lineNum) local line = editor:GetLine(_lineNum) return ( line:sub(1, self.boxStart:len()):lower() == self.boxStart:lower() ) end, -- checks if line has box.end LineIsEnd = function(self, _lineNum) local line = editor:GetLine(_lineNum) return ( line:sub(1, self.boxEnd:len()):lower() == self.boxEnd:lower() ) end, -- returns "false" if none error ErrorCheck = function(self) if self.selStart == self.selEnd then print("! NONE SELECTION.") return true elseif self.boxStart == "" or self.boxEnd == "" then print("! ERROR - The comment.box properties for *."..self.ext.." files are missing or incomplete.") return true elseif self.lineStart == self.lineEnd then print("! SINGLE LINE SELECTION. USE LINE COMMENT INSTEAD.") return true else return false end end, -- creates the text to toggle and replace the selection with it Toggle = function(self) self:Init() if self:ErrorCheck() then return end local uncomment = false local skip = 0 -- proceed with first line -- if start position is in empty line AND next line has box.start --> uncomment the block if self:LineIsEmpty(self.lineStart) and self:LineIsStart(self.lineStart +1) then uncomment = true skip = 1 -- the following line will ignored now -- if line from start position has box.start --> uncomment the block elseif self:LineIsStart(self.lineStart) then uncomment = true -- in other cases comment the block else -- insert box.start before the first line; if box.middle exists --> insert it too self.newText = self.boxStart.."\n"..self.boxMiddle..editor:GetLine(self.lineStart) end -- proceed with middle lines -- if box.middle is defined set/replace it in line local n = self.lineStart + 1 + skip local line while n < self.lineEnd do self.newText = self.newText..self:NewLine(n, uncomment) n = n + 1 end -- proceed with last line line = editor:GetLine(self.lineEnd) if not uncomment then self.newText = self.newText..self.boxMiddle..line..self.boxEnd else -- if uncomment the last line will ignored, but the trailing "\r\n" must deleted self.newText = self.newText:sub(1, -3) end -- replace the selection with the new toggled text editor:ReplaceSel(self.newText) end } BlockComment:Toggle() As far as I know, it is not possible to overwrite SciTE internal hotkeys. In this case "Ctrl+Shift+B" for IDM_BLOCK_COMMENT. Therefore I used the connection shown here.
      But if overwriting is possible, I would be interested in this solution.
      BlockComment.lua
    • By Bhooshan
      I need to mute an ongoing call on Microsoft teams without activating the window. Teams allows us to mute using shortcut key Ctrl+Shift+m but only when the window is active.
      # Used set option as ongoing call can be with any person which leads to change in Title Name.
      AutoItSetOption ( "WinTitleMatchMode", 2 ) 
      # I am not clear with the control ID which will be good to use here and also the key combination of ^M       
      ControlSend ( "Microsoft Teams", "", "[CLASS:Intermediate D3D Window; INSTANCE:1]", "{ctrl down}")
       
      Can anyone help...!!! 
       

    • By Sayed
      Hi there, 
      I'm new in AutoIt forms and using AutoIt to automate desktop application (able to automate the application normally but facing issue when I've to re-run the application twice within the same script...so need help in this please)
      here is the steps then followed by the issue in a brief : 
      1- run application . 
      2- do some actions (click menus,activate windows,set texts..)
      3- close the application. 
      4- run the application again & access the same controls.
      5- open the same windows again (like step 2)
      6- perform some validations (by getting texts from some text boxes)
      7- close the application again (and repeat 1-7 for 15 times in average )
      The issue 
      * all controls are accessible in the first run and actions done successfully on controls (for steps 1-3) BUT from the second run of the application from step-4 it's able to set focus only the main application window.
      Note: only unique properties used to while mapping the controls. 
      Error that appear in the console :
      UIAWrappers.au3" (1673) : ==> Array variable has incorrect number of subscripts or subscript dimension range exceeded.: $x = Int($t[1] + ($t[3] / 2)) $x = Int($t[1] + (^ ERROR  
      Simple spy code  of one of the controls that has this strange issue(menubar&view menu Item): 
      ;~ *** Standard code maintainable *** #include "UIAWrappers.au3" AutoItSetOption("MustDeclareVars", 1) _UIA_setVar("oP1","Title:=XXX;controltype:=UIA_WindowControlTypeId;class:=WindowsForms10.Window.8.app") ;main app form xxx _UIA_setVar("oP2","Title:=menuStrip1;controltype:=UIA_MenuBarControlTypeId;class:=WindowsForms10.Window.8.app") ;menuStrip1 ;~ $oUIElement=_UIA_getObjectByFindAll("View.mainwindow", "title:=View;ControlType:=UIA_MenuItemControlTypeId", $treescope_subtree) _UIA_setVar("oUIElement","Title:=View;controltype:=UIA_MenuItemControlTypeId;class:=") ;ControlType:=UIA_MenuItemControlTypeId;classname:=") ;~ Actions split away from logical/technical definition above can come from configfiles ;~_UIA_Action("oP1","highlight") _UIA_Action("oP1","setfocus") ;~_UIA_Action("oP2","highlight") _UIA_Action("oP2","setfocus") _UIA_action("oUIElement","highlight") ;~_UIA_action("oUIElement","click")  
       
    • By Fenzik
      Hello All!
      i suggest to set default encoding in Scite4 for Autoit 3 to UTF 8 with Bom encoding, format recommended also in Autoit Help.
      In last editor version, when i open new script, for example Czech characters (č, ř, ž) aren't correct.
      So when i change Encoding to UTF 8 with Bom from Default Code page property state, everithing seems to be OK.
      Thank you and sorry for potentialy duplicated content.
      Fenzik
    • By matwachich
      AutoIt3 Lua Wrapper
      This is an AutoIt3 wrapper for the Lua scripting language. Consider it beta software, but since I will be using it in commercial product, expect it to evolve.
      It has been developped with Lua 5.3.5. Updates will come for new Lua version.
      Everything works just fine, except one (big) limitation: Anything that throws a Lua error (using C setjmp/longjmp functionality) will crash your AutoIt program. That means that it is impossible to use throw errors from an AutoIt function called by Lua (luaL_check*, lua_error...).
      It is hosted in Github: https://github.com/matwachich/au3lua
      Simple example
      #include <lua.au3> #include <lua_dlls.au3> ; Initialize library _lua_Startup(_lua_ExtractDll()) OnAutoItExitRegister(_lua_Shutdown) ; create new execution state $pState = _luaL_newState() _luaopen_base($pState) ; needed for the lua's print function $iRet = _luaL_doString($pState, 'print("Hello, world!")') If $iRet <> $LUA_OK Then ; read the error description on top of the stack ConsoleWrite("!> Error: " & _lua_toString($pState, -1) & @CRLF) Exit EndIf ; close the state to free memory (you MUST call this function, this is not AutoIt's automatic memory management, it's a C library) _lua_close($pState)
×
×
  • Create New...