Tab completion with respect to one file type - powershell-4.0

How is it possible to restrict the tab completion to a specific file type? I think of an additional function x in powershell which only lists .tex files and starts the default or a specified program. I would like to type x doc to the shell, hit the tab key and ps complete it to x document.tex without respect to document.aux, .... Do you have an idea?

Related

Can I get bash completion to consider the text _after_ the cursor?

Motivating example:
I'm in a shell session in some directory, and I have three files: prefix_foo_suffix.txt, prefix_bar_suffix.txt and prefix_bar_another_suffix.txt. I've typed in: cat prefix_foo_suffix.txt, but I've changed my mind, I want the second file. So, I delete foo, and write b - only to realize I'veforgotten the name of that second file. So now my command-line is cat prefix_b_suffix.txt with the cursor after the b.
Now, if I press Tab, completion kicks in, but it gives me: prefix_bar_suffix.txt_suffix.txt which is not what I wanted.
Is it possible to get bash to consider the rest of the current word, or line, for completion? i.e. complete intra-word substrings to reach a relevant word?

Get Automator app result in external Applescript?

Is there a way to retrieve result of an Automator app script in an external Applescript app (not the Applescript lines in Automator)?
Something like:
tell application "My_Automator_App"
-- suppose My_Automator_App checks the Calendar to see if there some events today
-- "Show Result" in Automator will display a list
get the_Result -- list returned by Automator
end tell
I looked into this a little bit and didn't find a natural means by which AppleScript and Automator applets can communicate, although this doesn't mean one definitely doesn't exist.
In the meantime, you could implement one of a couple of workarounds/hacks that, although a little unseemly in their methods, do achieve the desired result without creating any side issues that would affect the functionality of an applet itself.
1. Use The Clipboard
Append a Copy to Clipboard action at the end of the applet's workflow, or following the action whose result you would wish to be reported.
Retrieving the clipboard from AppleScript is simple:
get the clipboard
This will probably suit return values that are simple text strings or a number. Passing an array of items from an Automator action to the clipboard isn't very reliable, sometimes only allowing access to the first item. However, this can be resolved with a small AppleScript within the workflow to process results arrays properly and convert them into an accessible format, e.g. a comma-delimited string.
However, the clipboard is also capable of storing image data, file references, and other data types, so it will be possible (if not always straightforward) to send those to be retrieved in an AppleScript.
Where possible, strings and numbers are the safest storage types.
2. Write Out To A Temporary File
To avoid using the clipboard as an intermediary, or if you wish the applet to report multiple variables without too much work, then writing the data to a temporary file is a fairly common practice, such as is done in shell scripts when persistant values are needed between multiple executions of the same script.
There's actually a special directory that gets periodically purged so that temporary data files don't accumulate: /tmp. It's hidden in Finder, but you can still create files and delete them as you would any other directory. Files that aren't access for 3 days get purged by the system.
There is a New Text File action that can write text to a file:
Specifying the /tmp directory is most easily done by creating a variable whose value is "/tmp" (without the quotes), and dragging that variable onto the appropriate field.
But my inclination would be to insert an AppleScript, or more suitably, a shell script into the workflow, with which file manipulation becomes easy and more capable.
Calendar Events Example
Using a similar example to the scenario you described, a simple applet that retrieves calendar events might have a workflow that looks like this:
where you can calibrate the first action to isolate the events you want, such as today's events. That action returns a type of object that isn't easily processed by AppleScript, but the second action extracts the relevant data in text format, summarising the list of events that the first action returned.
This is where a temporary file is useful to write out the data to a text file, which can then be retrieved in an AppleScript.
Given this Automator applet saved under the named "CalEvents", this AppleScript makes use of that applet and its result:
property tidEvents : [linefeed, linefeed, "EVENT", space] as text
property tidDetails : {tab, " to "}
property tid : a reference to my text item delimiters
run application id "com.apple.automator.CalEvents"
set tid's contents to tidEvents
set EventsSummary to read POSIX file "/tmp/EventsSummary.txt"
set EventsList to the EventsSummary's text items
set [[n], EventsList] to [it, rest] of EventsList
set n to n's last word as number
EventsList -- The final list of events from first to last
Upon its first run, the applet requires consent to access your calendar information, which only needs to be done once and will make the above script appear to fail. Once authorised, you can run the script as often as you like to get the most up-to-date content of the /tmp/EventsSummary.txt file.
Each item in the list variable EventsList is a block of text that looks like this (asterisks are my redactions for privacy, as are the address items in curly braces):
4 OF 8
Summary: GP Appointment
Status: none
Date: 07/12/2017 to 07/12/2017
Time: 14:45:00 to 15:45:00
Location: ******** Medical Centre
{Address Line 1}
{Address Line 2}
{County}
{Post Code}
United Kingdom
Notes: 01*** *****9
Each value is separated from the preceding colon by a tab character, which won't be obvious here. Also, as you can tell from the date format and address, these are British-formatted values, but yours will, of course, be whatever they are set as in Calendar.
But since each list item is much the same, extracting details for a particular event will be simple in AppleScript, first by splitting a particular event item into paragraphs, and then splitting a particular paragraph by either a tab or space character (or both) or some preposition that naturally delimits useful bits of text:
set |Event| to some item in the EventsList
set tid's contents to tidDetails
set EventDetails to {title:text item 2 of paragraph 2 ¬
, startTime:text item 2 of paragraph 5 ¬
, EndTime:text item 3 of paragraph 5} of the |Event|
which places the important event details, such as its name and start/end times, in an AppleScript record:
{title:"GP Appointment", startTime:"15:45:00", EndTime:"16:00:00"}

How to read firefox's about:config entries using Python?

How could I read about:config entries for firefox version 30.0 using Python ? I tried to use what is pointed by this answer (in JavaScript) but it did not help.
Yeah, that's a problem. Firefox comes with default values for most preferences, and only stores values different from the default in the profile. Added to this, each add-on may come with additional default values and create new preferences at runtime.
The default pref files might be contained within zip files, which complicates matters a little.
Files
Files you'd have to check for default preferences (in a standard Firefox distribution)
$APPDIR/omni.ja:greprefs.js
$APPDIR/omni.ja:defaults/preferences/*.js
$APPDIR/browser/omni.ja:greprefs.js
$APPDIR/browser/omni.ja:defaults/preferences/*.js
$PROFILE/extensions/*/defaults/preferences/*.js
$PROFILE/extensions/*.xpi:defaults/preferences/*.js
While preferences that were overridden from the default reside in $PROFILE/prefs.js.
So first you need to figure out $APPDIR (installation path of Firefox) and then $PROFILE (Firefox user profile path).
Then you need to read some files either in some directories (easy) or in some zip files (hard). A major problem is that you cannot just use zipfile to read omni.ja (and potentially some of the xpi files) because a typical python zipfile implementation is too rigid in the interpretation of the zip structure and fails to open these files. So you'd need your own zipfile implementation that can deal with this.
Format
In the *.js files there are essentially two types of lines (+ blank lines, comment lines):
pref("name", value)
user_pref("name", value)
The pref lines are default preferences, user_pref lines are user preferences (overridden from default).
Values
value is a Javascript expression such as "abc", true, 1 or 2 * 3. The latter is a problem, as you'd need a JS engine to properly evaluate it. But this isn't really a problem in practice, as you won't find expressions computing something in the wild (usually).
Conclusion
Really replicating the preferences system (or about:config) isn't an easy task and full of obstacles. It is probably far easier just reading user pref.js to see what's overridden and knowing the default values.
Example (just prefs.js)
import re
import json
PROFILE = "/path/to/firefox/profile"
def read_user_prefs(preffile):
r = re.compile(r"\s*user_pref\(([\"'])(.+?)\1,\s*(.+?)\);")
rv = {}
for l in preffile:
m = r.match(l)
if not m:
continue
k, v = m.group(2), m.group(3)
try:
rv[k] = json.loads(v)
except Exception as ex:
print "failed to parse", k, v, ex
return rv
with open("{}/prefs.js".format(PROFILE), "rb") as p:
prefs = read_user_prefs(p)
for k, v in prefs.items():
print u"({type:<16}) {key}: {value}".format(
key=k, value=v, type=str(type(v)))
print
print "Chrome debugging enabled:",
print prefs.get("devtools.chrome.enabled", False)
print "Last sync:",
print prefs.get("services.sync.tabs.lastSync", 0.0)
print "Pref that might not exist:",
print prefs.get("does.not.exist", "default")
Alternatives
Write a firefox-addon that dumps interesting Preferences to a known file, or uses another form of IPC (sockets, whatever) to communicate with your python script.

Snippets where content is conditional on language in Sublime Text 3?

Is there a way to create a single snippet file where the content output is dependent on the language? For example, keyboard shortcut x outputs "abc" when used in a css file, but "def" when used in a javascript file?
Snippets don't contain much processing capability — you can perform substitutions in them via Boost-style regexes and format strings, and they have access to a number of environment variables within Sublime such as the current file's name, the line number, etc., but beyond that they don't have much programmatic processing capability. It might be possible to set up a series of regexes that try to case-insensitively match $TM_FILENAME against \.css$ and output abc, then immediately match $TM_FILENAME against \.js$ and output def - only one of them will be successful.
However, in my mind such processing is much more easily handled by a plugin written in Python. The API documentation is mostly complete (all the functions you'll need are documented there) and there are a ton of examples around the net to learn/borrow from. Here's a quick example:
import sublime_plugin
class PrintScopeCommand(sublime_plugin.TextCommand):
def run(self, edit):
pos = self.view.sel()[0].begin()
scope = self.view.scope_name(pos)
if 'source.js' in scope:
self.view.insert(edit, pos, "This is JavaScript!")
elif 'source.css' in scope:
self.view.insert(edit, pos, "This is CSS!")
Save the file in your Packages/User directory (accessible via Preferences -> Browse Packages...) as print_scope.py. Next, assign it to a key binding by opening your user keymap (Preferences -> Key Bindings-User) and adding the following:
[
{ "keys": ["ctrl+alt+shift+p"], "command": "print_scope" }
]
if the file is empty. If you already have other custom key bindings, just add a comma , after the last one, then paste the line above after it, before the closing square bracket ].
You should now be able to hit CtrlAltShiftP (or whatever other key binding you choose), and if the file's syntax is set to JavaScript it will insert the This is JavaScript! message at the current cursor position. If the syntax is set to CSS, This is CSS! will print, and if the syntax is anything else, then nothing will print.

I get this window while editing Ruby Files in Vim. What is it?

I usually get this new window open up suddenly while I am editing a Ruby file in VIM. This is getting irritating because, i cant type in anything while its processing. And it usually happens arbitarily. Does any one here know which plugin could be doing this? Or is this somekind of VIM's process?
This is happening when you hit K in normal mode.
K Run a program to lookup the keyword under the
cursor. The name of the program is given with the
'keywordprg' (kp) option (default is "man"). The
keyword is formed of letters, numbers and the
characters in 'iskeyword'. The keyword under or
right of the cursor is used. The same can be done
with the command >
:!{program} {keyword}
There is an example of a program to use in the tools
directory of Vim. It is called 'ref' and does a
simple spelling check.
Special cases:
- If 'keywordprg' is empty, the ":help" command is
used. It's a good idea to include more characters
in 'iskeyword' then, to be able to find more help.
- When 'keywordprg' is equal to "man", a count before
"K" is inserted after the "man" command and before
the keyword. For example, using "2K" while the
cursor is on "mkdir", results in: >
!man 2 mkdir
- When 'keywordprg' is equal to "man -s", a count
before "K" is inserted after the "-s". If there is
no count, the "-s" is removed.
{not in Vi}
If you notice, it's running ri in the open window, which is the ruby documentation app.
In Unixy environments, the help program normally runs inline, just displacing the vim output for a minute.
Is this using gvim, or command-line vim?
In either case, you can try monkeying with 'keywordprg' to fix the popup
Or, if you can't train yourself not to type it, you can just use :nnoremap K k to change what K does (in this case, just treat it as normal k command and go up one line).
I have this same issue on my work desktop, but not my home machine. The setups are near identical.
While stalking down a possible cause, I noticed that when I leave my cursor over a Ruby symbol such as File, Vim would popup a short description of the File class. After comparing all the various vim scripts and ri-related files that I could find, I finally settled on the only solution that worked...
Open $HOME/_vimrc and add the following line:
autocmd FileType ruby,eruby set noballooneval
Previously, I commented out a block in $VIMRUNTIME/ftplugin/ruby.vim, but Brian Carper suggested a better solution of :set noballooneval. I added the autocmd line so it is only executed with Ruby files.
If anyone figures out a true solution, please contact me. :(

Resources