In today's world, User talk:The Transhumanist/SearchSuite.js has become a topic of great relevance and constant debate. With the advancement of technology and the constant evolution of society, User talk:The Transhumanist/SearchSuite.js has acquired a fundamental role in various fields, from politics and economics to culture and entertainment. Throughout history, User talk:The Transhumanist/SearchSuite.js has been the subject of study, analysis and discussion, leading to a wide range of opinions and perspectives on its importance and impact on everyday life. In this article, we will explore the different facets of User talk:The Transhumanist/SearchSuite.js and its impact on the modern world, as well as the implications it has for the future.
This is the workshop support page for the user script SearchSuite.js. Comments and requests concerning the program are most welcome. Please post discussion threads below the section titled Discussions. Thank you. By the way, the various scripts I have written are listed at the bottom of the page.
This script is operational in all skins except "Vector (2022)"
This script provides a menu of enhancements to search results. See description in the user manual below.
This search results modifier script is currently alpha software.
This is the work area for developing the script and its documentation. Even though this documentation is in user space, feel free to edit it. The talk page portion of this page starts at #Discussions, below.
Description & instruction manual for SearchSuite.js
This script is operational, and is under further development
For all the standard skins except MinervaNeue, this script provides a menu of enhancements to search results:
Add wikilink formatting, * ], for easy copying/pasting of list items
Each menu item is a toggle (an on/off switch), and the script remembers each switch's status across pages. If you turn a feature on (or off), it stays that way for all your searches until you click the menu item again.
The menu items appear on the side bar in the tools menu whenever you are on a search results page, which shows up after you've conducted a search.
The script also provides a (built-in) work-around for WP's "intitle:" bug, so that search results actually match the search string provided when using the "intitle:" parameter and enclosing your search term in quotes.
Important
This script is far from finished. If you'd like to comment, or contribute ideas or advice, please post under discussions at the bottom of this page. Post bugs in the bug report section. Thank you.
How to install this script
To make SearchSuite work on your account, add this line to your common.js (or your skin.js) page:
Save the page and bypass your cache to make sure the changes take effect. By the way, only logged-in users can install scripts.
Features / how to use
The script works on search results. To get a search results page, click on the magnifying glass in the search box and search for something. Or type intitle: in the search box, followed by your search term in quotes.
When you are on a search results page, the script provides the following additional menu selections on the sidebar's tools menu:
SR details
SR redirecteds
SR sisters
SR sort
SR wikify
"SR" stands for "search results". Each menu item includes a little note in parentheses indicating what clicking on it will do (either "(turn on)", or "(turn off)").
The script remembers each menu item's status between uses, and so each feature remains on or off for all of your searches until you click on its menu item again.
SR details
Turning this off strips out the extraneous details (the contents excerpt) between each entry, leaving the results displayed as one per line. This allows more results to be shown on the page at a time, and it is useful when copying/pasting to lists and outlines.
Turning it on brings the details back.
It is even more useful when used in combination with SR wikify.
SR redirecteds
Turning this off doesn't just remove the notes that say "redirect from", it removes the entire entries that include those notes. It also removes entries of items from related categories, and the results that match subheadings.
Turning it back on, adds those items back onto the list.
This feature helps narrow search results down to the topic entered.
SR sisters
This hides or shows the sister project results on the right side of the screen.
If you have the sister results turned off in Preferences, then this menu item has no effect.
SR sort
When this feature is turned on, the search results will appear in alphabetical order. To return them to their original order, click on SR sort (turn off).
SR wikify
As I'm a list editor, this is my favorite feature. This adds or removes list item wikiformatting to the title link of each entry in the search results. This is the same formatting you would see while you are in an edit window. This makes it easy to copy and paste the search results as list items into list and outline articles.
When you have details off and wikify on, your search results will look like this:
Notice that the links are still live, so that you can click on them.
Wikify is most useful when sort is turned on and the other features are turned off.
TrueMatch
The script includes a workaround for a bug in Wikipedia's search. The buggy (or misnamed?) feature of search is the parameter intitle:. When you include that in a search, the specified string is supposed to return only titles containing that string. But WP search doesn't limit the results that way, including matches with page contents, redirects, and pages from matching categories, and also containing matches of related forms of a lone word. For example, intitle:Greece also matches "Greek".
That's a problem, if you only want titles with "Greece" in them.
TrueMatch, which is a function built-in to this script, checks the search for "intitle:" followed by a quoted string. If it finds one, it removes all results that do not match the quoted string. It makes sure the search results actually match the intitle search string you provided.
To take advantage of TrueMatch you must include "intitle:" followed by a string in quotes. Here are some examples:
intitle:"France"
intitle:"in France"
Currently, TrueMatch only catches the first instance of intitle, and ignores everything else not within the quotes.
Quirks and known issues
There is a delay when using SRSort when the limit is set to 5000. (See tips and tricks, below).
The count of results listed is not amended when "redirecteds" is turned off. If you search on "Minorca" (with quotes) then turn off redirecteds, you only see 6 results instead of the advertised 20. That's because the script strips down the results returned by WP. I don't know how to fix this, but I'll keep thinking about it.
A similar thing happens when you use the "intitle:" parameter and the TrueMatch feature kicks in.
In the MinervaNeue skin, the features are stuck in whatever state they were in when the skin is selected. Unless there is a way to access the sidebar menu in this skin – if there is, please let me know. To turn features on, you would have to switch to another skin momentarily, click the menu items you wanted on, and then go back to the MinervaNeue skin.
Bug in wikEd: when you copy and paste single-spaced list items from the search results into wikEd, wikEd adds a blank line between them. Solution: Turn off wikEd temporarily, do the copy/paste, then turn wikEd back on.
Tips and tricks
To get the largest output of search results possible for a given search string, add &limit=5000 to the url, and press ↵ Enter. (The max in MediaWiki is 5,000).
Important: the following section is still under development and is incomplete. I work on it as I find the time.
Explanatory notes (source code walk-through)
This section explains the source code, in detail. It is for JavaScript programmers, and for those who want to learn how to program in JavaScript. Hopefully, this will enable you to adapt existing source code into new user scripts with greater ease, and perhaps even compose user scripts from scratch.
You can only use so many comments in the source code before you start to choke or bury the programming itself. So, I've put short summaries in the source code, and have provided in-depth explanations here.
My intention is Threefold:
to thoroughly document the script so that even relatively new JavaScript programmers can understand what it does and how it works, including the underlying programming conventions. This is so that the components and approaches can be modified, or used again and again elsewhere, with confidence. (I often build scripts by copying and pasting code that I don't fully understand, which often leads to getting stuck). To prevent getting stuck, the notes below include extensive interpretations, explanations, instructions, examples, and links to relevant documentation and tutorials, etc. Hopefully, this will help both you and I grok the source code and the language it is written in (JavaScript).
to refresh my memory of exactly how the script works, in case I don't look at the source code for weeks or months.
to document my understanding, so that it can be corrected. If you see that I have a misconception about something, please let me know!
In addition to plain vanilla JavaScript code, this script relies heavily on the jQuery library.
The most challenging thing about writing this script (so far) was figuring out how to make each of the menu-item-controlled functions work on the output of the others...
For sort, that meant recording the original order as an id in each list item element, so that they could be sorted back to that order later.
For the rest of the menu-item-controlled features, hide and show were used.
It turns out that if you hide an element, and you later show some of its children, the parent element is forced out of hiding. That's what happens with the hidden redirected entries. At least, I think that's what happened. So, in the functions (SRDetails) that affect the children, I had to recheck the setting of the parent, and rehide the parent according to the setting. Not very elegant. If you have a better solution, I'm very interested in learning it.
For the details of each search result, there was this extra space below each item, that didn't respond to hide/show. That space needed to be controlled via css block and inline display attributes. That was harder to figure out than it looks, because the output on screen was routinely copy and pasted into WikEd for use on other pages, and WikEd made it seem like there was an extra newline (\n in there by adding one in between each item, when there weren't any in the output, which led to a wild goose chase. The solution was to DuckDuckGo the hell out of the situation until a clue was revealed by Stack Overflow that mentioned something about list items being block elements with margin spacing rather than newlines. Then suspicion turned toward WikEd, so the script's output was then copied (from the screen via copy/paste) into Wikipedia's regular wiki editor instead where it was revealed that it was actually singlespaced, with no extra newlines in the script's output! Still, the extra spacing needed to be taken out for the list item views (to maximize how many are displayed on the screen at once), via injecting css code, but put back in along with the details, via more injected css code, so that the entries were restored back and forth to and from their original look.
More specifically, starting at the beginning of the source code...
Aliases
An alias is one string defined to mean another. Another term for "alias" is "shortcut". In the script, the following aliases are used:
mw is the alias for mediawiki (the mediawiki library)
These two aliases are set up like this:
(function(mw,$){}(mediaWiki,jQuery));
That also happens to be a "bodyguard function", which is explained in the section below...
Bodyguard function
The bodyguard function assigns an alias for a name within the function, and reserves that alias for that purpose only. For example, if you want "t" to be interpreted only as "transhumanist".
Since the script uses jQuery, we want to defend jQuery's alias, the "$". The bodyguard function makes it so that "$" means only "jQuery" inside the function, even if it means something else outside the function. That is, it prevents other javascript libraries from overwriting the $() shortcut for jQuery within the function. It does this via scoping.
The bodyguard function is used like a wrapper, with the alias-containing source code inside it, typically, wrapping the whole rest of the script. Here's what a jQuery bodyguard function looks like:
1(function($){2// you put the body of the script here3})(jQuery);
The script makes much use of mw.util.addPortletLink.
In order for mw.util.addPortletLink to work, the script is dependent upon the core module mediawiki.util, which contains its programming. (View the source code at mediawiki.util.js, and for its documentation, see mw:ResourceLoader/Core modules#mediawiki.util).
Therefore, it is necessary to declare (load) the module as a dependency.
(Keep in mind that scripts will work by accident without declaring dependencies, when another user script that was loaded earlier has already declared them for itself. If your script was working, but no longer works for no apparent reason, it may be because it doesn't load its dependencies.)
Dependencies are loaded with mw.loader.
The script includes the following dependency declaration:
mw.loader.using(,function(){// The rest of the script goes here });
Let's break this down...
mw is an alias that stands for mediaWiki. So, mw.loader is short for mediaWiki.loader.
mediaWiki.loader is a part of MediaWiki, the program that runs Wikipedia.
It has a number of methods defined for it. Its .using method executes a function as soon as the specified dependencies are ready, in this case, mediawiki.util.
The function, "function ()", is an anonymous function.
The code to be executed by a function is placed inside curly brackets: {}
And in this case, it's the rest of the script.
The ready() event listener/handler
The ready() event listener/handler makes the rest of the script wait until the page (and its DOM) is loaded and ready to be worked on. If the script tries to do its thing before the page is loaded, there won't be anything there for the script to work on (such as with scripts that will have nowhere to place the menu item mw.util.addPortletLink), and the script will fail.
The part of the script that is being made to wait goes inside the curly brackets. But you would generally start that on the next line, and put the ending curly bracket, closing parenthesis, and semicolon following that on a line of their own), like this:
1$(function(){2// Body of function (or even the rest of the script) goes here, such as a click handler.3});
mw.util.addPortletLink: the ResourceLoader module to add links to the portlets.
portletId: the id of the portlet (that is, menu) where the new menu item is to be placed. The various menus ("portlets") are::
p-navigation: Navigation section in left sidebar
p-interaction: Interaction section in left sidebar
p-tb: Toolbox section in left sidebar
coll-print_export: Print/export section in left sidebar
p-personal Personal toolbar at the top of the page
p-views Upper right tabs in Vector only (read, edit, history, watch, etc.)
p-cactions Drop-down menu containing move, etc. (in Vector); subject/talk links and action links in other skins
href: Link to a Wikipedia or external page (the initial purpose of portletlink was to link somewhere)
text: Text that displays in the menu (the title of the
id: HTML id (optional)
tooltip: Tooltip to display on mouseover (optional)
accesskey: Shortcut key press (optional)
nextnode: id of the existing portlet link to place the new portlet link before (optional) (Don't forget: ids have a leading "#")
The optional fields must be included in the above order. To skip a field without changing it, use the value null, that is, no space between the quotes for that parameter.
To place the menu items in alphabetical order, and so that they don't move around in the menu, for your last menu item specify the id of an existing menu item to anchor it. Then set "next node" for the next to last item as the id for the menu item you just set, and so on.
Important: All we've done so far above is assign mw.util.addPortletLink to a variable. It won't do anything until we bind the variable to a click handler (see below).
click handler
To make a menu item that does something when you click on it, you have to "bind" mw.util.addPortletLink, via its variable, to a handler. Like this:
(The variable used in this example is "portletlink").
1$(portletlink).click(function(e){2e.preventDefault();3//do some stuff4}
The "handler" is the part between the curly brackets.
What is the default being prevented? Portletlink's default action is to link somewhere. We don't want it to do that, and so that is what e.preventDefault(); is for.
Change log for SearchSuite.js
2017-11-11
Started script
Add subroutines for each of 4 menu items (without the guts)
SR detail
SR sisters
SR sort
SR wikify
Add guts for SR sister (it shows/hides sister project results)
Add temporary guts for SR sort (same as in StripSearchSorted)
2017-11-12
Got the initial 4 menu items to display in menu in correct order
Made "SR wikify" so it disappears when details are turned on
Replace nested activation filters that check for a condition existing with consecutive deactivation filters that end the program via return statement if a condition does not exist. Reduces indentation, resulting in a cleaner script.
Sandwich the main links in entries with link wikicodes, which are themselves sandwiched between classed spans
Add menu item and guts for toggling the hiding of descriptions (details) from search results (class='searchresult')
Add menu item and guts for toggling the hiding of redirs and categories from search results
Add menu item and guts for toggling the hiding of sister stuff from search results
Add menu item and guts for toggling the hiding of link wikicodes
Add menu item for toggling sort (without the guts)
2018-02-16
Set menu items to appear in alphabetical order by assigning ids to next node parameters
Anchored Wikify menu item to precede Special pages menu item
Run Wikify first, to prevent link wikicode from being shown by default
2018-02-17
Sort entries alphabetically, rewrite the sort function for "SRSort (turn on)" using "detach" approach, using a search algorithm found on stackoverflow
Put the control contructs in functions, in case they ever need to be called from more than one place
2018-02-18
Add numerical ids to list items to record their original order
Sort entries by numerical ids to restore their original order --> the guts for "SRSort (turn off)"
THE BASIC SCRIPT APPEARS TO BE FULLY OPERATIONAL (toggles for detail, redirected, sister, sort, and wikify)
For SRDetail (turn off), change search results to display: "inline" to remove extra whitespace
For SRDetail (turn on), change search results back to display: "block" to restore extra whitespace
2018-03-08
Fixed bug in SRDetailsOn() and SRDetailsOff() that was forcing list items with .altsearchtitle to show (making the SRRedirected switch appear like it wasn't working). Added redundant code to hide those elements again. A bit clunky, but it works.
2018-03-09
Removed vector skin deactivation filter. I've tested it on all skins, and it seems to work, but only partially on MinervaNeue. Still testing with MinervaNeue (features are stuck in whatever state they were in when skin is selected, unless I can find the menu).
2018-03-23
Fix mouseover tips (the text was wrong in eight of them)
Fix details switch malfunction (no longer affects redirecteds display)
Task list
Test the sort/unsort with larger lists (set to 5000) Done - it seems to work correctly, even with long lists
Correct the text in the popup boxes when hovering over the switches in the side bar. The first three say "hide" when they should say "show" & v.v. On the fourth one, Sort, the text implies that the Details setting is also toggled, which it isn't: Noyster (talk),18:03, 11 March 2018 (UTC) Fixed
Noyster reported on Feb 26th (in discussion section below) that number at bottom of page is wrong when redirecteds are hidden – 08:18, 23 March 2018 (UTC)
All the numbers at the bottom of the page are wrong when redirecteds is in use (clicking on them won't display the number listed, because entries will have been stripped out). – 08:18, 23 March 2018 (UTC)
All the numbers at the bottom of the page are wrong when intitle:"" is included in the search (invoking TrueMatch) – 08:18, 23 March 2018 (UTC)
Cities intitle:"List of" returns zero results (you can see many before the filter kicks in). 04:12, 26 March 2018 (UTC)
Desired/completed features
Completed features are marked with Done
True Match: Partially fixes the "intitle:" bug (default feature) Done implemented in StripSearchSorted, which was reforked to here. Though it only fixes it for search strings included in quotes.
Sandwich the main links in entries with link wikicodes, which are themselves sandwiched between classed spans Done
Menu item for toggling the hiding of details from search results (class='searchresult') Done
When details (turn on) is clicked, show the details Done
When details (turn off) is clicked, hide the details Done
Menu item for toggling the hiding of redirs and categories from search results Done
Menu item for toggling the hiding of sister stuff from search results Done
Menu item for toggling the hiding of link wikicodes Done
Menu item for toggling the sort setting Done — menu item is in place, but is non-operational
Have the menu items display in alphabetical order and stop jumping around Done
When sort (turn on) is clicked, sort the entries alphabetically Done
When sort (turn off) is clicked, sort the entries back to original order Done
The wikibrackets start as showing, but they should be hidden Done
BASIC SCRIPT OPERATIONAL
When details (turn on) is clicked, show the extra white space between entries Done (in css, display: "block")
When details (turn off) is clicked, hide the extra white space between entries Done (in css, display: "inline")
Menu item to turn "match case" for intitle searches off/on (or "case-sensitivity" on/off)
Search tools heading in sidebar
Filter feature (to further filter the search results)
Some way of clearing the status memory (for testing)
Make TrueMatch correct for all strings, not just those in quotes
Make TrueMatch catch multiple instances of intitle
Make TrueMatch parse intitle searches, and process all valid uses of it
Catch user's syntax errors in use of the intitle parameter, and display the instructions for intitle
Feature to set views to user desired value (up to 5000)
A switch (menu item) to turn the whole program off (for testing purposes)?
Add a try catch?
Development notes for SearchSuite.js
Sorting a copy and then swapping the copy in/out
One of the toggles is to sort and unsort.
I'm not sure if the various other toggles will work with the StripSearchSorted approach. It "unsorts" by returning to a previous state.
Theoretically, it should, so I'll try it. But it needs the wikibracketing sequence stripped out, as I put that into its own function.
I seem to have scrambled everything. Took out too much, I think. Now Ill just try taking out the wikibracketing.
Approach 1: Have the non-sort functions affect both versions
This will be the first approach, because it is already mostly in place.
Using a copy for the sort version, and the original or the unsorted version...
If the other menu items modified both, it shouldn't matter which one is being displayed.
Approach 2: Have both sort functions sort
Sort (turn off) would sort to original order.
Sort (turn on) would sort to alphabetical order.
Development notes for SearchSuite.js for pre-2018-02-03 version
(2017-11-12) Okay, the menu items work relative to each other, and now it is time to add guts to their subroutines so that clicking the menu items actually does something...
SRSisterOff() and SRSisterOn() are easy, as they show and hide the element #mw-interwiki-results (which lies outside the search results), respectively, and this is already implemented. The placement of the sister results however must not be changed by the re-generation of the search results as it currently does for some unknown reason -- this bug needs to be fixed.
For the rest to work, we need a behind-the-scenes function -- SRArray() -- that puts the search entries into an array (SRArray) and maps out a new array that rebuilds each entry along with new classes inserted, so that we can hide/show inter-entry spacing, details, and additional link delimiters.
SRSortOn will sort SRArray.
SRSortOff will restore the original order in SRArray.
SRDetailOff will hide the details in SRArray.
SRDetailOn will show the details in SRArray.
SRWikifyOn() and SRWikifyOff() will show and hide wikicode generated in the SRArray function, respectively. These functions should activate only when details are off. When details are turned off, SRWikify needs to be turned on. When details are turned on, SRWikify needs to be turned off.
If the entries can't be rebuilt without the extra line, then we'll have to do something more involved...
There are 4 combinations:
DetailOff SortOn – if #Array2 exists, remove it. Hide original results, add #Array1 (has no details, and includes wikilinkage class).
DetailOn SortOn – if #Array1 exists, remove it. Hide original results, add #Array2 (has details) and sort it.
DetailOff SortOff – If #Array2 exits, remove it. If #Array1 exists, show it, else hide original results and create it.
DetailOn SortOff – if #Array1 exists, remove it. If #Array2 exits, remove it. Show original results.
SRWikifyOn() and SRWikifyOff() will show and hide wikicode generated in the SRArray function, respectively. These functions should activate only when details are off. When details are turned off, SRWikify needs to be turned on. When details are turned on, SRWikify needs to be turned off.
Rough design
Before anything has been changed:
Get the entries into an array.
Map that into another array without line feeds (SRArray)
With each part classed (can use original classes, except for whichever one includes the line feed)
SRLink = Link
SRDesc = Description
SRData = Data
SRLF = Line feed
SRWikicode = Bullet and link brackets
Get display modes from local storage
SRMode
SortOffDetailOn
SortOffDetailOff
SortOnDetailOn
SortOnDetailOff
WikiLinksMode (on/off)
InterwikiMode (on/off)
The script needs to show the results in current display mode
SRMode
WikiLinksMode (on/off)
InterwikiMode (on/off)
The script needs to change the mode based on menu item clicks
The hard part is a pair of menu items, each with 2 states, that affect each other.
One pair is to turn sorting on and off:
Turn sorting on (sort)
SortOnDetailOn
Set SRMode = SortOnDetailOn
Remove insertedDiv
Hide the original results
.after(id=insertedDiv).append SRArray
.sort()
Show SRLink
Show SRDesc
Show SRData
Show SRLF
SortOnDetailOff
Set SRMode = SortOnDetailOff
Remove insertedDiv
Hide the original results
.after(div).append SRArray
.sort()
Show SRLink
Hide SRDesc
Hide SRData
Hide SRLF
Turn sorting off
SortOffDetailOn
Set SRMode = SortOffDetailOn
Remove insertedDiv
Hide the original results
.after(id=insertedDiv).append SRArray
Show SRLink
Show SRDesc
Show SRData
Show SRLF
SortOffDetailOff
Set SRMode = SortOffDetailOff
Remove insertedDiv
Hide the original results
.after(div).append SRArray
Show SRLink
Hide SRDesc
Hide SRData
Hide SRLF
The other pair is to turn details off and on:
Turn details off (hide details and extra linefeeds)
SortOffDetailsOff
SortOnDetailsOff
Turn details on (show details)
SortOffDetailOn
SortOnDetailOn
Script dependencies
Discussions
This is where the actual talk page starts for SearchSuite.js. Please post your discussion threads below...
Search intitle: doesn't work right with quoted strings that include a space
intitle:"word1 word2" (notice the space between the words) returns results that do not have the search string in the title.
It seems to happen for any search string with a space in it.
So, intitle:"Milan" produces only items with Milan in their titles, while intitle:"in Milan" includes items which has this in the title, but also includes items that have this only in the article contents and not in the title. This seriously waters down the search results.
This happens to me too. Rather annoying. It seems contrary to spec too? If my recollection is correct it was working correctly, or at least much better, two to three months ago? Eno Lirpa (talk) 00:46, 22 October 2017 (UTC)
I think it's because "in" is a common word which is ignored in some search contexts. I get 400 hits on both intitle:"in Milan" and "in Milan" intitle:Milan. The latter seems to be the actual search performed for both. intitle:"word1 word2" works as expected in my tests with two uncommon words. For example, intitle:"Inter Milan" gives me 56 hits, and all have the quote in the title. PrimeHunter (talk) 01:25, 22 October 2017 (UTC)
The first one I would like to add is a menu item for turning the sorting of search results on/off. It will sort the results whether or not they've been stripped yet.
Another one will insert/remove wikilink formatting. (Not everyone will want the link delimiters displaying all the time).
And more.
My question for you is this: what do I need to think about in approaching the writing of this script, with its various menu item features (that are intended to work together)?
I look forward to reading your thoughts on this matter.
I think the basic approach to this would be to set classes for elements you want to show/hide, because then the code for the menu items themselves becomes really easy: when clicked, you just hide/show the relevant classes, i.e. searchSuite-foo-show and searchSuite-foo-hide for elements that should be shown/hidden when foo is activated (and then reversed when foo is turned off). Sorting is going to more tricky to do/undo, but basically you would store data about the original order, then write functions like sortAlpha and sortOrig that would operate on the containing element, replacing it's contents with sorted contents. For a simpler example, to sort the links in the toolbox, you could do
I'm not really sure, just be aware anything one feature might change has to be accounted for when coding the other features. - Evad3717:09, 9 November 2017 (UTC)
Activation filter for article namespace pages?
On some of my scripts, I use an activation filter that checks the title and runs only if the namespace up there matches:
// Run this script only if "Book:" is in the page titleif(document.title.indexOf("Book:")!=-1){// (Body of script goes here)};
Now I need to do this with articles in the main namespace, but there is no prefix up there in the title to work off of.
Yep, you can do something like that, for any namespace (namespace numbers are listed at WP:NS). Or check for the inverse situation, so you don't have to nest everything inside an if statement:
// Run this script only for main namespaceif(mw.config.get('wgNamespaceNumber')!==0){return;};// (Body of script goes here)
The return statement only works within functions, but that's generally not a problem – you're whole script is usually wrapped inside a function, assuming you need to wait for the document ready and/or wait for resource loader modules to be loaded. - Evad3700:44, 12 February 2018 (UTC)
Many of my scripts approach an insane level of if statement nesting. I definitely need to apply this return approach.
I think your program snippet above means "If the namespace is not 'zero', end the function." And "return" ends the program if the body of the script is in the same function, and at the same level (or deeper) in that function, as the if statement. Am I reading that right? The Transhumanist14:38, 12 February 2018 (UTC)
Yes, the "return" ends the function it is immediately within at the point, and so the program resumes execution from the point where the function was invoked – but since we've wrapped the whole script in $( function($) {...}); there's nothing more left to execute, and so the script ends. It doesn't matter if the "return" is within any number of "if"/"if-else" statements, "for" loops, "while" loops, etc – only having another (sub)function will change the scope it applies to. One thing to watch for, at deeper levels within your programs, is that when you are assigning a variable to a function call (var foo = someFunction(bar);), the variable is set to the return value, which is specified with "return someValue;" inside the function. Since we haven't explicitly set a return value, it would be undefined – but that doesn't matter for our purpose, since the function is just there to make the script wait before executing, and is not assigning a value to a variable. - Evad3702:09, 13 February 2018 (UTC)
Based on your explanations above, I've written the following deactivation filters using return statements:
// ============== deactivation filters ==============// End the script if Vector skin is not the user's skinif(mw.config.get('skin')!=='vector'){// use a return statement to end the local function and hence the program's body// important: this approach does not work outside of a functionreturn;}// End the script if " - Search results - Wikipedia" is not in the page titleif(document.title.indexOf(" - Search results - Wikipedia")==-1){// use a return statement to end the local function and hence the program's body// important: this approach does not work outside of a functionreturn;}
Are these correct?
And am I using the correct terminology in my comments?
What about doing the same thing for more than one namespace? Such as "run script if the page is in the article namespace or the template namespace"? The Transhumanist18:03, 13 February 2018 (UTC)
@The Transhumanist: You just need to negate the logic to work out when to return. NOT( isArticle OR isTemplate ) is equivalent to isNotArticle AND isNotTemplate. So in script (and putting the actual namespace number into a variable to avoid duplication), you get something like:
// Run this script only for main and template namespacesvarnamespaceNumber=mw.config.get('wgNamespaceNumber');if(namespaceNumber!==0&&namespaceNumber!==10){return;};// (Body of script goes here)
Or you could go a bit further and assign the condition to a variable, so you can name it (makes it easier to read, and remember what you were doing), and negate it later with the ! operator:
// Run this script only for main and template namespacesvarnamespaceNumber=mw.config.get('wgNamespaceNumber');varisArticleOrTemplate=(namespaceNumber===0||namespaceNumber===10);if(!isArticleOrTemplate){return;};// (Body of script goes here)
And that's alright for a couple of namespaces, but if you need to do more, rather than keep adding more ORs or ANDs to the condition, you can use the array method indexOf for the logical test (which returns -1 if a value isn't in the array tested)
// Run this script only for main and template namespacesvarnamespaceNumber=mw.config.get('wgNamespaceNumber');varallowedNamespaces=;// main, user, template, modulevarisInAllowedNamespace=(allowedNamespaces.indexOf(namespaceNumber)!==-1);if(!isInAllowedNamespace){return;};// (Body of script goes here)
The main thing that's "wrong" with your code is your usage of localStorage. If for some reason localStorage isn't available (e.g. it is full, or the user has turned it off, or the user's browser doesn't have localStorage), it will throw up an error and stop executing your script. Any time you use localStorage storage, you should be using a try/catch structure, which looks like this:
try{// Code that might generate an error goes here// The script will execute up until an error occurs, at which point it moves to the catch block,// or until the end of the try block, at which point it skips the catch block}catch(e){// Code to execute if there is an error – i.e. if you can't read a value from localStorage, just assume a default value// The error details are in the `e` parameter, which you can output the browser console like this:console.warn(e);}// Script continues here, even if there was an error encountered in the try block
As for optimisation, it depends on what you mean. For speed/efficiency, that's pretty much taken care of by the browser. Most of the time, any optimisations you can make are on the order of milliseconds, which really don't matter unless you are doing millions of operations. What's more important to optimise how easily you can read, reason about, and make changes to your code. Which is actually a very, very, broad topic – look up "code refactoring" or "clean code" – but what I can think of at the moment is:
Make function and variable names meaningful, such that you don't need comments to understand what they do. Use sentence fragments, starting with a verb for functions. E.g. instead of TrueMatch, you could have something like removeResultsWithoutIntitleString()
Avoid having identical or near-identical code blocks – instead, create a function, which you you can pass a parameter into if needed to account for the slight differences
If your function is meant to be doing one thing (based on either name or comment), avoid doing other things in the same in the same function. E.g. your "Function to sort the search results" is also doing stuff related to menu items and localStorage. It would probably be better in a separate function that also gets called from SRSort().
The constant creating, removing, and recreating of menu items is a bit weird and unnecessary. Creating them is really part of the prep work. The rest of your program the just needs to be able to show and hide them from the user – i.e. using jQuery's .hide() and .show() – as appropriate. So initially that would be based on the localStorage values, and then updated each time SRWikify(), SRSort(), etc are called.
Hmmm. Try catch. So that's what TheDJ was talking about. (But he mentioned it in relation to mw module calls, like when they're not available for some reason). You make it seem to simple. Assume a default value. If local storage doesn't return a value, pick a mode. On or off. That makes sense. One try catch for each local storage variable? Five try catches are needed then?
I'm not sure I understand your last comment, as I couldn't think of any other way to implement a toggle. But I'll tinker around with it. Will work on the try catch thing first, though.
This is a feature I would like to add, to let the user further hone down the search results. I think TrueMatch could be cloned and adapted to do this, but in order to parse an additional search string, the program will need an input form. I've never done one of those before. Any guidance would be most helpful. The Transhumanist20:06, 24 February 2018 (UTC)
You can use the prompt() method to request user input. W3Schools has a couple of good examples: - Evad3704:36, 25 February 2018 (UTC)
I was thinking about including fields for a string to include, a string not to include, and a checkbox for regex. :) I took a look at JWB to see if I could understand that source code, and it's in Greek! The Transhumanist17:04, 25 February 2018 (UTC)
Let the user set the view limit
The search results have links at the bottom for setting the number of items to be displayed to 20, 50, and so on, up to 500. But the API allows setting at any number up to 5,000, with &limit=5000.
I'd like a menu item that allows the user to choose their own limit. Then the program would need to pass the &limit command to the API. I don't know how to do that.
Again, you can use the prompt method, and then load a new url based on the current url using location.replace(url-string) - Evad3704:36, 25 February 2018 (UTC)
I was thinking in terms of a stored setting, but I guess local storage could be used in conjunction with this. Along with a try catch, of course. :) I'll give it a go. The Transhumanist18:06, 25 February 2018 (UTC)
Quibbles with "redirecteds" feature
Been trying out this very useful tool & found these niggles with the "redirecteds" feature:
If you turn this setting to "off" at the sidebar, the setting is not remembered (as it is with the other 4 settings). On the next search, "redirecteds" will again be on.
The count of results listed is not amended when "redirecteds" is turned off. If you search on "Minorca" (with quotes) then turn off redirecteds, you only see 6 results instead of the advertised 20.
I don't see where it says in the documentation that "redirecteds", as well as showing redirected entries and entries from matching categories, also brings up entries where a section heading includes the search term.
@Noyster: It turned out there were two bugs causing switch malfunction you reported. One was a typo in a variable. The other was another function inadvertently showing the previously hidden material. (If you access any children elements in the HTML source, the parent element apparently is forced from hiding). So I added some redundant code to turn it off again. The switches should all work now. — The Transhumanist04:22, 9 March 2018 (UTC)
Thank you. I do hope this search tool will become available in other skins soon. Like about 2 million of us, I'm a Monobook type and had to change to Vector to try this out. Didn't enjoy it as every page looked the same as if I was logged out ): Noyster (talk),11:41, 9 March 2018 (UTC)
@Noyster: Done I removed the restriction and have tested SearchSuite in all skins. To my surprise and delight, it works fine in them all except for a quirk in MinervaNeue. In that skin, the features are stuck in whatever state they were in at the time the skin was activated. Unless the sidebar is available somehow. If it is, let me know. I only did a rudimentary check on MonoBook, so be sure to let me know how well it works for you. — The Transhumanist14:14, 9 March 2018 (UTC)
@Noyster and Evad37: Any ideas? We're stripping down the results provided by WP's search. It would be easier to adjust the number to how many are showing than to boost the number of results back up to the number shown. But, the other numbers still wouldn't provide the amount of results they specify. The hidden results are still there, they are just, well, hidden. Except with TrueMatch, those results are gone. You'd have to do another search without intitle to get those back.
While we are on the subject of using the script, how often do you use the switches, or do you leave them in a particular configuraton? Of so, what switch settings do you have set? I usually leave mine set at: Details=off, Redirecteds=Off, Sisters=Off, Sort=On, and Wikify=On. How about you?
For me: Details=Off, Redirecteds=On, Sisters=Off, Sort=On, and Wikify=Off, but often use the switches.
On numbering: It hardly matters while confined to a handful of enthusiasts, but when this comes into general use as I hope it will, when Redirecteds are Off it won't look professional to see maybe as little as 6 results on a list that "should" show 20. So with Redirecteds Off it might it be best to eliminate the line at the bottom
@Noyster: I fixed the mouseover tips, so they now accurately describe what clicking on each menu item will do. I've confirmed your report of a conflict between the details toggle and the redirecteds status. Apparently, turning details on or off makes the redirecteds disappear. I'll see if I can track down what is causing this. Thanks for the heads up; nice catch. — The Transhumanist08:09, 23 March 2018 (UTC)
@Noyster: I think I fixed the details/redirecteds switches malfunction. Now, both switches should work correctly regardless of each other's status. Thank you for the bug report. — The Transhumanist09:20, 23 March 2018 (UTC)
SearchSuite suggestion
Hello and thanks again for User:The Transhumanist/SearchSuite.js which I find very useful. May I suggest another switch, to turn off the suppression of non-matching entries? For example, I'm currently searching for linksto:"Adventure" intitle:"film" (because many of those articles should link to Adventure film instead), but I need to comment out SearchSuite in my common.js to see any results. Thanks, Certes (talk) 09:38, 27 July 2018 (UTC)
Aha! The problem is that intitle: wasn't the first thing in my search. Line 147 of SearchSuite.js sets intitle to linksto:"Adventure" film, and line 151 doesn't find that string in any article titles. An extra .* in line 145 might fix it, as in RegExp('.*intitle:"(.+?)".*','i'), but I've not tested that change. Certes (talk) 23:41, 29 July 2018 (UTC)
Screenshots
Great work on this. Amazing functionality. How about adding some screenshots so users can see what it looks like? – Lionel(talk)01:51, 29 April 2018 (UTC)
Have you thought about moving the documentation to User:The_Transhumanist/SearchSuite.js/doc ? Then you could use this page as a real talk page. – Lionel(talk)01:51, 29 April 2018 (UTC)
It works for me. Looking at your example above more closely, it appears that there is a space after the colon following "intitle". That means that the string following the space is a separate search parameter, treated normally. If you take out the space, your intitle search works as expected in SearchSuite, with SearchSuite stripping out the results that do not match. — The Transhumanist10:29, 18 September 2018 (UTC)
I don't understand the question. Though the program currently only accepts "intitle:" at the beginning of the search, I think. I'll have to check. The "TrueMatch" feature definitely needs some refinement. — The Transhumanist00:02, 18 September 2018 (UTC)
@The Transhumanist: currently when I search intitle: "(TV Series)" I get results for "TV series" as well (lower-case "s"). Is there a setting I need to enable to get only results for "Series" with an upper-case "S"? --Gonnym (talk) 00:17, 18 September 2018 (UTC)
Fixed For some reason, I had made it case insensitive, which on retrospect, seems pretty silly for a feature called "TrueMatch". Perhaps, at the time, I didn't know what the "i" modifier at the end meant (I did a lot of copying/pasting code when I built the program). This time though, I spotted it right away, and removed it. The script works as you requested, though you may have to up the search results to 5,000 when searching for "TV Series". To do that, click on "50" down where it says "View". Then in the URL, change limit=50 to limit=5000, and press ↵ Enter.
It will take a bit more programming to provide a menu item to turn case-sensitivity for intitle searches on/off, but I'll start working on it. Thanks for the suggestion!
Note that the highest setting, via the URL, is 5,000 (for non-admins), and that Wikipedia's search feature only shows up to the 10,000th result. You get an error message after that. SearchSuite is a filter that modifies Wikipedia's search results, so that the number shown is less than what WP returned. So for "TV Series", there are only 3 matches in the first 5,000 results, so it shows 3 even though the View indicates 5,000. What's happening is that MediaWiki doesn't honor "intitle", and returns results where the search term isn't in the title. Keep in mind that SearchSuite isn't a direct search engine; it just modifies or filters the results returned by MediaWiki. In other words, for intitle searches, it searches the search results.
Concerning your question, since I just made the fix, you may still be accessing the old code from your cache. So, you need to clear your cache. I went to the program page and did a purge just now, in case it is the server cache, but I don't know if that is user-specific (I don't see why it would be). After clearing your cache, try the search again, and let me know if it works. (Keeping my fingers crossed). — The Transhumanist10:29, 18 September 2018 (UTC)
P.S.: "TrueMatch" is a built-in function, though somebody else requested that it be put on a switch like the rest of the features. That may be tricky, since it only applies to intitle searches, and people may be confused why it wouldn't do anything to regular searches. I'll need to think about it more. — The Transhumanist10:44, 18 September 2018 (UTC)
@The Transhumanist: Cleared my cache several times, got rid of anything related to Wikipedia or Wikimedia and even logged in on a different browser, but still not working for me. And yeah, toggle options are always good. --Gonnym (talk) 11:34, 18 September 2018 (UTC)
There should be no space between "intitle:" and "TV Series", like this intitle:"TV Series" If you have an intervening space, it will treat the search string as a normal entry. — The Transhumanist11:50, 18 September 2018 (UTC)
@The Transhumanist: - Came here to request the same thing about an on/off sidebar toggle for TrueMatch. Consider this a +1 vote. There are other toggles that don't appear to do anything, depending on the results being shown at the time. You could maybe call the sidebar text for it "SR intitle TrueMatch" or something like that. -- Netoholic@19:29, 30 March 2019 (UTC)
Deactivation filter
Hi. Checking the document title makes the script run only in english wikipedia. What if you make it checking if mw.config.get('wgCanonicalSpecialPageName') === 'Search' ? -- geraki(talk)16:34, 14 August 2019 (UTC)
Stopped working
A few days ago, this script stopped working for me. It's not misbehaving; it just does nothing. Is it still working for anyone else? Certes (talk) 11:59, 31 January 2021 (UTC)
@Ajpolino: I'm using Firefox 85 on Ubuntu 16.04. Do you also use Firefox? I know Mozilla have recently tightened up security and I'm wondering if that could be preventing the script from running. However, other scripts such as DisamAssist and Linkclassifier work normally for me. Certes (talk) 00:26, 13 February 2021 (UTC)
I do indeed! Firefox 85 on Windows 10. However, I just tried logging in and doing some searches in Edge and Chrome, and still no luck. Ajpolino (talk) 00:30, 13 February 2021 (UTC)
Thanks, Sam Sailor; your version works for me too. I can see how the 31 Jan change prevents an undefined function from being called but I think it's legitimate to call the main function without a SRFilter and expect all its other goodness still to happen. Perhaps we could move the if(typeof SRFilter === 'undefined') test so that, when false, it skips only line 121 SRFilter(); and still allows the rest of the code to execute. Certes (talk) 13:56, 7 June 2021 (UTC)
You're both very welcome. I can't say I use the functionality of this script often, but I certainly miss it a lot when it isn't working, and I happen to need it. Many thanks to The Transhumanist, splendid script! SamSailor18:42, 7 June 2021 (UTC)
@Certes, Ajpolino, and Sam Sailor: Hi. I'm happy you find SearchSuite.js useful. I would have answered sooner, but I have it loaded at the browser level, so I can tinker with it without affecting the project-installed code, so I didn't notice it wasn't working for anybody else. And my watchlist is broken. (I'd like to wipe it, but with 156,000+ entries, that causes it to time out upon trying to edit it.) It's stuck, with such a long list of changes that it renders it useless, and it won't let me start it over from scratch. However, pings do work to reach me. I was pinged when Sailor mentioned my nym above, 4+ months after the initial post. I hope you guys weren't inconvenienced for that long. I'm glad you sorted it out. Feel free to keep in touch. Feedback, ideas, and comments are welcome. — The Transhumanist11:42, 12 June 2021 (UTC)
@The Transhumanist: Thanks again for the useful script. I'm surprised that Edit raw watchlist fails; it does no clever formatting and is instant for me, but my list is much smaller. There is a "Clear watchlist" nuclear option (wikilink Special:EditWatchlist/clear) if all else fails. Certes (talk) 13:24, 12 June 2021 (UTC)
@Certes: Thank you for the nuke tip. All cleared. It listed all the pages from the portal namespace of old, which is largely irrelevant now. Cheers, — The Transhumanist08:03, 13 June 2021 (UTC)
Hello. I have found this script to be extremely helpful, especially with the redirecteds feature which I use often, but I've come across a strange bug where when intitle: is used in a search, redirected entries seem to automatically be hidden, regardless of whether SR redirecteds is toggled to on or off. Could you look into this? Thanks in advance! InfiniteNexus (talk) 22:39, 11 January 2024 (UTC)
@InfiniteNexus: I'm looking into it, and will keep in touch. You are using the Vector legacy (2010) skin? It doesn't seem to work at all in the Vector (2022) skin -- the script's menu doesn't even show up in that. By the way, have you had issues with thumbnail images in the search results? — The Transhumanist19:57, 27 January 2024 (UTC)
Yes, I am using V10; like the Visual Editor, I will never switch to V22 until and unless its long list of limitations and issues is addressed. I have not noticed any issues with thumbnails, but that is possibly because I mainly make use of the redirecteds feature, as I mentioned earlier. InfiniteNexus (talk) 00:52, 29 January 2024 (UTC)
Date is the onlookers
Anderson has been installed on a machine that has the latest trends on his computer system
RedlinksRemover.js – remove red linked list items that are end nodes (last item of a branch), reiteratively, and delink the rest, from outlines and lists.
Search results page enhancements
SearchSuite.js – suite of search features, each on a switch, so you can turn them on and off as desired (and it remembers the switch positions). SearchSuite replaces all the search scripts below.
StripSearchSorted.js – provides menu item that turns sorted strip search on/off; Includes the features of all the other search scripts below, and sorts the results alphabetically. Co-written by User:Evad37; he did the heavy-duty programming. StripSearch.js – provides menu item that turns strip search on/off; strips search results down to bare pagenames. StripSearchSansRedirecteds.js – strips search results down to bare pagenames, with redirected entries removed. No off switch. StripSearchInWikicode.js – strips search results down to bare pagenames, and presents as bullet list with pagenames enclosed in double square bracket link delimiters (just like in wikicode). Redirected entries are also removed. No off switch.
StripSearchSimple.js – strips all search results down to bare pagenames. No off switch.
Viewing enhancements for list and outline editors hunting for list items
ViewAsOutline-AllPagesWithPrefix.js – adds list item wikicodes to the on screen results of All pages with prefix, for easy copying/pasting into outlines and lists. No off switch.
ViewAsOutline-Category.js – removes the alphabetical headings, and adds list item wikicodes, for easy copying/pasting into outlines and lists. No off switch. ViewAsOutline-Book.js – converts page to outline format on screen, with wikicodes for easy copy and paste into outlines and lists. No off switch. ViewAsOutline-CategoryTree.js – on menu item click, converts tree to outline format on screen, with wikicodes for easy copying/pasting into outlines and lists. Refresh page to undo. ViewAsOutline-Templates.js – converts navboxes and sidebar boxes on current page into outline format, with wikicodes displayed, for easy copying/pasting into outlines. No off switch. (Needs to be enhanced to show base links rather than pipes.)
ViewAsOutline-Glossary.js – converts glossaries to list format on screen, with wikicodes for easy copy-and-paste into outlines and lists. No off switch. (In early development, very rough. Currently, only converts bullet list glossary format.).
Coming eventually
QuickPortal.js – portal tool, for creating and restarting portals. Will be expanded for modification and maintenance as well.
OutlineDedupeHolding.js – remove duplicate list items from the outline's holding sections (See also, holding bin, place these, general concepts, and list section). That is, it will remove from each of these sections, in turn, all topics that exist anywhere else in the body of the page (not in templates). StripSearchFilter.js – narrow down search results. OutlineMain2LI.js – convert main links in outline to list items. TopicPlacerFromBin.js – Topic placer (loads topics from holding bin into an array, then assists in placing each one). For use on lists and outlines. FetchCategory.js – import category to present location. FetchCategories.js – import categories to tagged locations. FetchSection.js – import section to present location.
TopicSender.js – prompts for parent topic (outline), then checks
if it is already there, if it isn't, then it sends it to the receiving section of that outline) PlaceCategory.js –
OutlineViewConventional.js – change the viewed formatting of the current outline into that of a conventionally indented outline, without headings.