Is there a quick way to add gettext() calls to strings in PyDev? - eclipse

Is there a quick way to add a gettext() call to a literal string in the PyDev editor running under Eclipse? I.e. when I place the cursor on any literal 'string' in a Python file, I want to turn this into _('string') with a single keypress. Can I use macros or something like that to add such functions?

It should be possible to do that with some simple Python scripting inside PyDev.
Take a look at: http://pydev.org/manual_articles_scripting.html (you can use https://github.com/aptana/Pydev/blob/master/plugins/org.python.pydev.jython/jysrc/pyedit_import_to_string.py as an example).
For the text selection, the PySelection implementation may be found at: https://github.com/aptana/Pydev/blob/master/plugins/org.python.pydev.core/src/org/python/pydev/core/docutils/PySelection.java (so, you can see how getSelectedText and work your own version to get the text you want).

Here is a little PyDev script that I was able to create with the hints given by Fabio. If you press Ctrl+2,t then the literal string at the cursor position will be surrounded with a gettext call. I'm not sure whether I'm using the Java API as expected, but it works for me. If you have ideas for improvement, please comment.
if cmd == 'onCreateActions':
from org.eclipse.jface.action import Action
from org.python.pydev.core import IPythonPartitions
from org.python.pydev.core.docutils import ParsingUtils, PySelection
class AddGettext(Action):
"""Add gettext call around literal string at cursor position."""
GETTEXT = '_'
def run(self):
sel = PySelection(editor)
doc = sel.getDoc()
pos = sel.getAbsoluteCursorOffset()
ctype = ParsingUtils.getContentType(doc, pos)
if ctype == IPythonPartitions.PY_SINGLELINE_STRING1:
char, multi = "'", False
elif ctype == IPythonPartitions.PY_SINGLELINE_STRING2:
char, multi = '"', False
elif ctype == IPythonPartitions.PY_MULTILINE_STRING1:
char, multi = "'", True
elif ctype == IPythonPartitions.PY_MULTILINE_STRING2:
char, multi = '"', True
else:
char = None
if char:
par = ParsingUtils.create(doc)
if multi:
start = par.findPreviousMulti(pos, char)
end = par.findNextMulti(pos, char)
else:
start = par.findPreviousSingle(pos, char)
end = par.findNextSingle(pos, char)
doc.replace(end + 1, 0, ')')
doc.replace(start, 0, self.GETTEXT + '(')
ACTIVATION_STRING = 't'
WAIT_FOR_ENTER = False
editor.addOfflineActionListener(
ACTIVATION_STRING, AddGettext(), 'Add gettext call', WAIT_FOR_ENTER)

Here is another solution using Vrapper:
:map gt ca'_(<esc>pa)<esc>
Note that this only works with single-quoted strings, it does not recognize when you use double quotes or multi-line strings.

Related

Split a string based on "|" character in PowerShell

I have a string variable in PowerShell which contains the value:
NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8
I am attempting to get the beginning portion of that string into it's own variable by identifying the index of the "|" character and using a substring function to extract the first portion of the string, in this case "NFP". I am not sure how to escape the "|" so I can use it properly. It doesn't seem to recognize it at all. My latest attempt is as follows:
$PolicyManual = $Item["PolicyManual"]
write-host $PolicyManual #Displays NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8
if ($PolicyManual.Contains([regex]::escape("|"))) {
$PolcyManual = $PolicyManual.Substring(0, $PolicyManual.IndexOf([regex]::escape("|")))
}
I'm sure this is simple, but I can't figure out how to make it work. Can anyone offer assistance to a PowerShell novice?
Thanks.
The problem is that .contains method doesn't know about regex and you are never entering the if condition because of this. When you do [regex]::escape("|"), the method is looking for a literal \|.
Try this instead:
$PolicyManual = "NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8"
if ($PolicyManual.Contains('|')) {
$element0, $element1 = $PolicyManual.Split('|')
$element0 #=> NFP
$element1 #=> 8dc3b47a-48eb-4696-abe2-48729beb63c8
}

GTK EntryCompletion by insertion instead of replacement

I've built a GTK application with autocompletion in an Entry, but I'd like the selected "completion" string to be replace the only word that the cursor touches, whereas it currently replaces all text in the Entry.
I can use set_match_func on the EntryCompletion to deliver matches based on only the word that is adjacent to the cursor, but I don't see how to override the text-insertion behaviour. Is there a way for me to do this?
I'm working in Ruby with gtk3. (I linked the doc for gtk2 because for the life of me, I can't find a complete doc for gtk3 in Ruby.)
Edit Here's my implementation (in Ruby), which lacks the desired "insert" behaviour:
module MyAutocomplete
# Add autocomplete to a Gtk::Entry object
def self.add entry, &block
model = Gtk::ListStore.new String
model.append.set_value 0, 'sd'
model.append.set_value 0, 'foo'
model.append.set_value 0, 'six'
completion = Gtk::EntryCompletion.new
completion.set_minimum_key_length 0
completion.set_text_column 0
completion.set_inline_completion true
completion.set_model model
completion.set_match_func do |*args|
self.match_func *args
end
yield(model, completion) if block_given?
entry.set_completion completion
end
def self.match_func(entry_completion, entry_value, list_obj)
len = 0 # Counts characters into the entry text
cursor = entry_completion.entry.position
entry_text = entry_completion.entry.text
entry_tokens = entry_text.scan(/[\w+#]+|[^\w#]+/)
current_token = entry_tokens.find { |tok|
(len += tok.length) >= cursor && tok =~ /\w/
}
obj_text = list_obj.get_value(0)
return current_token && obj_text.start_with?(current_token)
end
end

how to read a multiline element from PySimpleGUI

My program stub looks like this:
import PySimpleGUI as sg
layout = [[sg.Text("Geheime Nachricht eintippen:")],
[sg.Multiline(size=(70,4),key="GEHEIM")],
[sg.Spin([i for i in range(1,26)], initial_value=12, key="SS"), sg.Text("Schlüssel zwischen 1 und 25 wählen")],
[sg.Radio("Codieren:", "RADIO1", key="XX" ,default=True),
sg.Radio("Decodieren:","RADIO1", key="YY")],
[sg.Text("ERGEBNIS:")],
[sg.Multiline(size=(70,4),key="AUSGABE")],
[sg.Button("Weiter"), sg.Button("Ende")]]
window = sg.Window("Geheimcode", layout)
while True: # Ereignisschleife
event, values = window.Read()
geheimertext = values("GEHEIM")
print(values("GEHEIM"))
schluessel = int(values["SS"])
print ("Schlüssel = ", schluessel)
if values["XX"] == True:
codedecode = "C"
print("wir codieren:",codedecode)
else:
codedecode = "D"
print("wir decodieren:",codedecode)
if event is None or event == "Ende":
break
window.Close()
The program-line geheimertext = values("GEHEIM") gives this error:
TypeError: 'dict' object is not callable
I quess that the multiline generates a dictonary in the dictionary values?
so my simple newbie-question is how to read the multiline of a gui made with pysimpleGUI
ok, one possible solution is to iterate over the elements of the multiline:
geheimertext=""
for zeichen in values["GEHEIM"]:
geheimertext = geheimertext +zeichen
print(geheimertext)
Is there a better solution? Please teach a newbie
print(values["GEHEIM"])
values is a dict, and not a callable, so you cannot use () brackets (callables are functions or objects that have a function property). You can access to values through [] brackets. values["GEHEIM"].

How to cut a string from the end in UIPATH

I have this string: "C:\Procesos\rrhh\CorteDocumentos\Cortados\10001662-1_20060301_29_1_20190301.pdf" and im trying to get this part : "20190301". The problem is the lenght is not always the same. It would be:
"9001662-1_20060301_4_1_20190301".
I've tried this: item.ToString.Substring(66,8), but it doesn't work sometimes.
What can I do?.
This is a code example of what I said in my comment.
Sub Main()
Dim strFileName As String = ""
Dim di As New DirectoryInfo("C:\Users\Maniac\Desktop\test")
Dim aryFi As FileInfo() = di.GetFiles("*.pdf")
Dim fi As FileInfo
For Each fi In aryFi
Dim arrname() As String
arrname = Split(Path.GetFileNameWithoutExtension(fi.Name), "_")
strFileName = arrname(arrname.Count - 1)
Console.WriteLine(strFileName)
Next
End Sub
You could achieve this using a simple regular expressions, which has the added benefit of including pattern validation.
If you need to get exactly eight numbers from the end of file name (and after an underscore), you can use this pattern:
_(\d{8})\.pdf
And then this VB.NET line:
Regex.Match(fileName, "_(\d{8})\.pdf").Groups(1).Value
It's important to mention that Regex is by default case sensitive, so to prevent from being in a situations where "pdf" is matched and "PDF" is not, the patter can be adjusted like this:
(?i)_(\d{8})\.pdf
You can than use it directly in any expression window:
PS: You should also ensure that System.Text.RegularExpressions reference is in the Imports:
You can achieve it by this way as well :)
Path.GetFileNameWithoutExtension(Str1).Split("_"c).Last
Path.GetFileNameWithoutExtension
Returns the file name of the specified path string without the extension.
so with your String it will return to you - 10001662-1_20060301_29_1_20190301
then Split above String i.e. 10001662-1_20060301_29_1_20190301 based on _ and will return an array of string.
Last
It will return you the last element of an array returned by Split..
Regards..!!
AKsh

Typoscript: how do I add a parameter to all links in the RTE?

I want to add a parameter to all links entered in the RTE by the user.
My initial idea was to do this:
lib.parseFunc_RTE.tags.link {
typolink.parameter.append = TEXT
typolink.parameter.append.value = ?flavor=lemon
}
So for example:
http://domain.com/mypage.php
becomes
http://domain.com/mypage.php?flavor=lemon
which sounds great -- as long as the link does not already have a query string!
In that case, I obviously end up with two question marks in the URL
So for example:
http://domain.com/prefs.php?id=1234&unit=moon&qty=300
becomes
http://domain.com/prefs.php?id=1234&unit=moon&qty=300?flavor=lemon
Is there any way to add my parameter with the correct syntax, depending on whether the URL already has a query string or not? Thanks!
That would be the solution:
lib.parseFunc_RTE.tags.link {
typolink.additionalParams = &flavor=lemon
}
Note that it has to start with an &, typo3 then generates a valid link. The parameter in the link also will be parsed with realURL if configured accordingly.
Edit: The above solution only works for internal links as described in the documentation https://docs.typo3.org/typo3cms/TyposcriptReference/Functions/Typolink/Index.html
The only solution that works for all links that I see is to use a userFunc
lib.parseFunc_RTE.tags.link {
typolink.userFunc = user_addAdditionalParams
}
Then you need to create a php script and include in your TS with:
includeLibs.rteScript = path/to/yourScript.php
Keep in mind that includeLibs is outdated, so if you are using TYPO3 8.x (and probably 7.3+) you will need to create a custom extension with just a few files
<?php
function user_addAdditionalParams($finalTagParts) {
// modify the url in $finalTagParts['url']
// $finalTagParts['TYPE'] is an indication of link-kind: mailto, url, file, page, you can use it to check if you need to append the new params
switch ($finalTagParts['TYPE']) {
case 'url':
case 'file':
$parts = explode('#', $finalTagParts['url']);
$finalTagParts['url'] = $parts[0]
. (strpos($parts[0], '?') === false ? '?' : '&')
. 'newParam=test&newParam=test2'
. ($parts[1] ? '#' . $parts[1] : '');
break;
}
return '<a href="' . $finalTagParts['url'] . '"' .
$finalTagParts['targetParams'] .
$finalTagParts['aTagParams'] . '>'
}
PS: i have not tested the actual php code, so it can have some errors. If you have troubles, try debugging the $finalTagParts variable
Test whether the "?" character is already in the URL and append either "?" or "&", then append your key-value pair. There's a CASE object available in the TypoScript Reference, with an example you can modify for your purpose.
For anyone interested, here's a solution that worked for me using the replacement function of Typoscript. Hope this helps.
lib.parseFunc_RTE.tags.link {
# Start by "replacing" the whole URL by itself + our string
# For example: http://domain.com/?id=100 becomes http://domain.com/?id=100?flavor=lemon
# For example: http://domain.com/index.html becomes http://domain.com/index.html?flavor=lemon
typolink.parameter.stdWrap.replacement.10 {
#this matches the whole URL
search = #^(.*)$#i
# this replaces it with itself (${1}) + our string
replace =${1}?flavor=lemon
# in this case we want to use regular expressions
useRegExp = 1
}
# After the first replacement is done, we simply replace
# the first '?' by '?' and all others by '&'
# the use of Option Split allow this
typolink.parameter.stdWrap.replacement.20 {
search = ?
replace = ? || & || &
useOptionSplitReplace = 1
}
}